我正在尝试从class component
to react hooks
with Context API
,我无法弄清楚出现错误的具体原因是什么。
首先,我的代码:
// contexts/sample.jsx
import React, { createContext, useState, useContext } from 'react'
const SampleCtx = createContext()
const SampleProvider = (props) => {
const [ value, setValue ] = useState('Default Value')
const sampleContext = { value, setValue }
return (
<SampleCtx.Provider value={sampleContext}>
{props.children}
</SampleCtx.Provider>
)
}
const useSample = (WrappedComponent) => {
const sampleCtx = useContext(SampleCtx)
return (
<SampleProvider>
<WrappedComponent
value={sampleCtx.value}
setValue={sampleCtx.setValue} />
</SampleProvider>
)
}
export {
useSample
}
// Sends.jsx
import React, { Component, useState, useEffect } from 'react'
import { useSample } from '../contexts/sample.jsx'
const Sends = (props) => {
const [input, setInput ] = useState('')
const handleChange = (e) => {
setInput(e.target.value)
}
const handleSubmit = (e) => {
e.preventDefault()
props.setValue(input)
}
useEffect(() => {
setInput(props.value)
}, props.value)
return (
<form onSubmit={handleSubmit}>
<input value={input} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
)
}
我得到的错误:
不变违规:无效的挂钩调用。钩子只能在函数组件的主体内部调用。发生这种情况的原因之一可能是: 1. 您的 React 和渲染器版本可能不匹配(例如 React DOM) 2. 您可能违反了 Hooks 规则 3. 您可能在其中拥有多个 React 副本相同的应用程序 请参阅https://reactjs.org/warnings/invalid-hook-call-warning.html https://reactjs.org/warnings/invalid-hook-call-warning.html有关如何调试和解决此问题的提示。
我的代码的解释:
I used Context API
来管理状态,之前我用过class component
s 提出意见。我希望结构很简单,不需要更多细节。
我认为它也应该有效,<Sends />
组件被传递到useSample
HoC 函数,它被包裹起来<SampleProvider>
的组成部分sample.jsx
, 以便<Sends />
可以使用props
由提供SampleCtx
语境。但结果是失败。
使用是否无效HoC
图案与React hooks
?或者传递变异函数是否无效(即setValue
由制成useState()
)通过其他组件props
?或者,放置2个或更多是无效的function components
using hooks
在一个文件中?具体原因是什么,请指正。