[英]Is this the correct way to set the state of parent component in react.js
[英]Correct way to update a state inside useReducer (React.js)
我有兩個“選擇”輸入 (html) 可以用來顯示信息,這是 state:
const [foodValues, setFoodValues] = useState({ type: 'Everything', category: 'Everything' })
一切正常,我在兩個輸入上都使用了經典的 handleChange():
const handleChange = e => {
const value = e.target.value
const name = e.target.name
dispatch({type: ACTIONS.CHANGE, payload: {e: value, name: name}})
}
如你所見,我調用 dispatch 來使用 useReducer:
const OperationsReducer = (foodReducer, action) => {
const { foodValues, setFoodValues } = useContext(AllContext)
switch (action.type) {
case ACTIONS.CHANGE:
setFoodValues({
...foodValues,
[action.payload.name]: action.payload.e
})
break;
}
}
它工作得很好:但是我在控制台中收到了這個警告:
警告 不要在 useEffect(...)、useMemo(...) 或其他內置 Hooks 中調用 Hooks。 你只能在 React function 的頂層調用 Hooks。 有關詳細信息,請參閱
所以,我的問題是:有沒有辦法在沒有警告的情況下使用這個 useReducer ? 我知道我可以在它之外使用 setFoodValues,但我很好奇(我真的很喜歡使用 useReducer ...)。 我已經閱讀了關於這個主題的 React 文檔,但是我看到有些人做了一些非常奇怪(而且很酷)的事情來解決這個問題。
const initialState = { type: 'Everything', category: 'Everything' };
function reducer(state, action) {
switch (action.type) {
case ACTIONS.CHANGE:
return {
...state,
[action.payload.name]: action.payload.e
};
default:
return state;
}
}
function Component() {
const [state, dispatch] = useReducer(reducer, initialState);
const handleChange = e => {
const value = e.target.value
const name = e.target.name
dispatch({type: ACTIONS.CHANGE, payload: {e: value, name: name}})
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.