![](/img/trans.png)
[英]How to make functional update of reactjs state object property correctly inside useEffect hook
[英]how to update an object using useEffect in Reactjs and Typescript
我對Reactjs
+ Typescript
非常陌生,我試圖弄清楚為什么我會收到以下錯誤。
React 16.9
const STEP_STATUS = {
COMPLETED: "Completed",
INCOMPLETE: "Incomplete",
};
const Foo = () => {
const [state, setState] = useState({
step: 1,
firstName: '',
lastName: '',
status: STEP_STATUS["INCOMPLETE"],
});
const nextStep = () => {
setState({...state, step: state.step + 1});
}
useEffect(() => {
if (state.step + 1 !== state.step) {
// setState(prev => {...prev, state.step = STEP_STATUS["COMPLETED"]}); // I tried this too
setState(...state, state.status = STEP_STATUS["COMPLETED"]);
} else {
console.log("error"); // don't mind this line
}
}, [state]);
我正在嘗試使用useEffect
創建副作用,在按下按鈕nextStep
(將用戶帶到下一頁)后,我想在進入下一頁之前將當前頁面的狀態更新為“已完成”。
我可能真的做錯了。
任何幫助都會非常有幫助。
×
TypeError: state is not iterable
53 | useEffect(() => {
54 | if (state.step + 1 !== state.step) {
55 | // setState(prev => {...prev, state.step = STEP_STATUS["COMPLETED"]});
> 56 | setState(...state, state.status = STEP_STATUS["COMPLETED"]);
| ^ 57 | } else {
58 | console.log("error");
59 | }
您需要在 setState 調用周圍放置 object 大括號,如下所示:
setState({...state, status: STEP_STATUS["COMPLETED"]})
還建議使用傳遞給 setState 的 prevState 值進行更新,以防止關閉。
我認為使用整個state
作為useEffect
掛鈎上的依賴數組並不是一個好主意。 這實際上將導致在useEffect
掛鈎中更新state
時出現無限循環,這將導致它被一遍又一遍地觸發。
看看您要實現的目標,我相信state.step
應該在依賴數組上。 此外,您使用了錯誤的語法來引用 object 中的屬性。 您應該使用冒號( :
,而不是使用等號( =
)。
useEffect(() => {
setState({
...state,
status: STEP_STATUS["COMPLETED"]
});
}, [state.step]);
如果您嘗試使用setState
中的回調,則可以修改為:
setState((prevState) => ({
...prevState,
status: STEP_STATUS["COMPLETED"]
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.