這是我第一次使用useReducerand useContextwithTypescript并且我正在創建一個簡單的計數器。我正在嘗試更新countusing increment 和 decrement dispatch,但它沒有改變,終端也沒有錯誤。
這是codeandbox的鏈接: codesandbox
謝謝
uj5u.com熱心網友回復:
使用背景關系時,Provider需要在組件樹上比使用者更遠。代碼中最重要的組件是App,它會立即嘗試執行useContext(CountContext)。但是由于上面沒有提供者,所以 App 只是獲取背景關系的默認值,這意味著dispatch是一個空函式() => {}。
您需要拆分組件。在樹的頂部附近渲染提供者,然后在樹的更遠的地方使用它。例如:
function App() {
return (
<CountContextContainer>
<SomeChildComponent/>
</CountContextContainer>
);
}
function SomeChildComponent() {
const { state, dispatch } = useContext(CountContext);
const increment = () => {
dispatch({
type: ActionType.INCREMENT,
payload: 2
});
};
const decrement = () => {
dispatch({
type: ActionType.DECREMENT,
payload: 2
});
};
return (
<div className="App">
<p>Count: {state.count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/382663.html
上一篇:Angular:關于表單更改事件
