我使用上下文api为经验丰富的钩子创建了一个计数器,但一切正常,但是我有一个警告:
警告:calculateChangedBits:期望返回值是一个31位整数。而是收到:未定义
export const CountCtx = createContext(0, () => {});
function CountContext() {
const [count, setCount] = useState(0);
return (
<div className="cp1">
<CountCtx.Provider value={[count, setCount]}>
<p>Component where i created the context 'CountCtx'<br/>Counter is {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<ComponentA/>
</CountCtx.Provider>
</div>
)
}
function ComponentA() {
const [count, setCount] = useContext(CountCtx);
return (
<div className="cp2">
<p><b>Component A</b><br/>Counter is {count}</p>
<button onClick={() => setCount(0)}>Reset</button>
<ComponentB/>
</div>
)
}
function ComponentB() {
const [count, setCount] = useContext(CountCtx);
return (
<div className="cp3">
<p><b>Component B</b><br/>Counter is {count}</p>
<button onClick={() => setCount(count -1)}>Decrement</button>
</div>
)
}
非常感谢,我不明白此警告:-/
答案 0 :(得分:0)
createContext
中的第二个参数是undocumented calculateChangedBits
callback function。
由于提供了无效的回调,因此这会阻止上下文工作:
export const CountCtx = createContext(0, () => {});
应该是:
export const CountCtx = createContext(0);
答案 1 :(得分:0)
createContext在使用函数作为参数时期望返回值。您使用的函数没有返回值。因此,代替
export const CountCtx = createContext(0, () => {});
应该是
export const CountCtx = createContext(0, () => {return 1}); or export const CountCtx = createContext(0, () => 1);