简体   繁体   English

React.useState() 钩子不反映新值

[英]React.useState() hook doesn't reflect new value

QUESTION: Why my setContact() function doesn't work?问题:为什么我的 setContact() function 不起作用?

My hook declaration:我的钩子声明:

const [contact, setContact] = useState({
fName: "",
lName: "",
email: ""});

My UI element:我的用户界面元素:

<input
      name="email"
      placeholder="Email"
      onChange={catchEmail}
      value={contact.email}
    />

My onChange handler:我的 onChange 处理程序:

function catchEmail(event) {
const { value: email } = event.target;
setContact((prevValue) => {
  prevValue.email += email;
  return prevValue;
});

} }

I know how to make it work, but I want to understand what's wrong with this code.我知道如何使它工作,但我想了解这段代码有什么问题。

Changing the DOM is (sometimes) expensive.更改 DOM(有时)很昂贵。 React, understanding this, does not re-render components if the new state is exactly the same ( === ) as the old state.如果新的 state 与旧的 state 完全相同 ( === ),React 理解这一点不会重新渲染组件。

Here, since you're mutating the existing state and returning it, the new state is the same object as the old state, so React skips re-rendering. Here, since you're mutating the existing state and returning it, the new state is the same object as the old state, so React skips re-rendering.

You need to return a new object, so React knows to re-render.您需要返回一个的 object,以便 React 知道重新渲染。

setContact(prevValue => ({
  ...prevValue,
  email
}));

(you don't want to concatenate onto the existing email value, you want to set the new email state value to the new full input value, almost certainly) (您不想连接到现有的email值,您想将新的email state 值设置为新的完整输入值,几乎可以肯定)

You can also avoid this problem by separating out the different stateful values, eg, do:你也可以通过分离不同的状态值来避免这个问题,例如,这样做:

const [email, setEmail] = useState('');
onChange={e => setEmail(e.target.vaue)}

as is usually recommended with hooks.通常建议使用挂钩。

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

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