我有一个简单的React组件,名为Child
,当单击时,它会增加其计数.此外,还保存了一个外部状态,该状态在Child
组件递增时更新.
const Child = ({ onChange }) => {
const [count, setCount] = useState(0);
return (
<div>
<h1
onClick={() => {
setCount(prev => prev + 1);
onChange(1);
}}
>
Child count = {count}
</h1>
</div>
);
};
const App = () => {
const [count, setCount] = useState(0);
return (
<div className="App">
<h1> Parent Count = {count} </h1>
<Child onChange={(i) => setCount(count + i)} />
</div>
);
}
上述代码按预期工作.然而,当我使用上下文API来管理外部状态时,Child
组件的内部计数保持在0
.
const App = () => {
const [count, setCount] = useState(0);
const AppContext = React.createContext();
return (
<div className="App">
<AppContext.Provider value={{ state: count, setState: setCount }}>
<>
<AppContext.Consumer>
{({ state }) => <h1> Parent Count = {state} </h1>}
</AppContext.Consumer>
<AppContext.Consumer>
{({ state, setState }) => (
<Child onChange={(i) => setState(state + i)} />
)}
</AppContext.Consumer>
</>
</AppContext.Provider>
</div>
);
};
样品CodeSandbox.
为什么AppContext.Provider
内元件的内部状态总是重置为其初始状态?