如何使用钩子设置计算属性的状态 [英] How to setState of computed property using hooks

查看:72
本文介绍了如何使用钩子设置计算属性的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在更新我的一个旧项目,以尽可能使用钩子而不是一直使用状态.我基本上是在重构这个项目,并根据我从那以后学到的东西让它变得更好.

so I'm updating an old project of mine to use hooks wherever possible instead of state all the time. I'm basically refactoring the project and making it better based on what I've learnt since.

我遇到了这个

handleChange(event){
   setState({ [event.target.name]: event.target.value })
}

我为组件中的其他值创建了一个 useState 挂钩,但我不知道如何为计算属性设置状态.

I have created a useState hook for other values in the component but I don't know how I'd go about setting state for a computed property.

Password: <input className= "userNameBox" type="password" name="password" value={this.state.password} onChange={this.handleChange} onKeyPress={this.enterPressed.bind(this)}></input>

上面是我调用相关方法的地方.

Above is where I call the method incase that's relevant.

谁能告诉我我会在这个方法中改变什么才能使用钩子?

Could anyone tell me what I would change in this method in order for it to use hooks?

推荐答案

使用 hooks,需要使用 功能更新 使用 prevState 因为它不像 this.setState 等效.

With hooks, you need to use functional updates with prevState because it doesn't merge with previous state like with this.setState equivalent.

请参阅合并状态更新.

const Component = () => {
  const [value, setValue] = useState({ password: "" });
  const onChange = ({ target: { name, value } }) => {
    setValue((prevState) => ({ ...prevState, [name]: value }));
  };
  return <input name="password" value={value.password} onChange={onChange} />;
};

这篇关于如何使用钩子设置计算属性的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆