简体   繁体   English

React 使用 setState 更新嵌套的 object

[英]React use setState to update nested object

I'm trying to update a nested object in React using setState , which is in a function that is called from a form onChange event.我正在尝试使用setState更新 React 中的嵌套 object ,它位于从表单onChange事件调用的 function 中。 The code below works the first time it is called, but after that I get an error Cannot set properties of undefined (setting 'value') .下面的代码在第一次被调用时工作,但之后我得到一个错误Cannot set properties of undefined (setting 'value') What am I doing wrong?我究竟做错了什么?

const initialState = {
    email: { value: "", hasError: true, error: "" },
    password: { value: "", hasError: true, error: "" }
}

const [state, setState] = useState(initialState);

function handleChange(event) {
    setState(state[event.target.name].value = event.target.value);
}

You cannot setState like that.你不能这样设置状态。 You need to get the previous value from setState.您需要从 setState 中获取先前的值。 There is a prev argument in setState that allows you to pass the previous values into the function. setState 中有一个 prev 参数,允许您将先前的值传递到 function。 You can use the spread operator to keep all untouched values the same.您可以使用扩展运算符来保持所有未触及的值相同。 For instance:例如:

const initialState = {
    email: { value: "", hasError: true, error: "" },
    password: { value: "", hasError: true, error: "" }
}

const [state, setState] = useState(initialState);

function handleChange(event) {
    setState(prev => ({
      ...prev,
      email: {
        value: "value",
        hasError: false,
        error: ""
      }
    }));
}

Also - You can just check if there's an error by evaluating the error property.另外 - 您可以通过评估error属性来检查是否有错误。 Something like ?.state?.email?.error so you don't need the extra boolean in there (obviously if there's an error string, then it means there's an error).?.state?.email?.error这样的东西你不需要额外的 boolean 在那里(显然如果有一个错误字符串,那么这意味着有一个错误)。 Just clear the error string on reset and it'll be false again.只需在重置时清除错误字符串,它就会再次为假。

Info on setState: https://reactjs.org/docs/faq-state.html#what-does-setstate-do关于 setState 的信息: https://reactjs.org/docs/faq-state.html#what-does-setstate-do

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM