使用动态键对 setState 做出反应 [英] react setState with dynamic key
问题描述
我有以下代码片段:
onChange(e) {
e.persist
this.setState((prevState) => {
prevState[e.target.id] = e.target.value
return prevState
})
}
我将如何使用类似上面的代码为每个键设置状态.
the how would i set the state for each key using something like the code above.
这是初始状态:
this.state = {
heading: this.props.match.params.length > 1 ? "Edit Post" : "Create Post",
title: '',
category: '',
body: '',
author: ''
}
推荐答案
基本规则是:
我们可以使用计算属性名称 概念并使用任何 js 表达式 来动态计算对象属性名称.为此,我们需要将表达式放在 []
中.
We can use Computed property names concept and use any js expression to compute the object property name dynamically. For that we need to put the expression inside []
.
像这样:
var obj = {
[10 * 20 + 1 - 5]: "Hello"
};
console.log('obj = ', obj);
解决方案:
根据你贴的代码,你需要把e.target.id
放在[]
里面,像这样:
As per the code you posted, you need to put e.target.id
inside []
, like this:
onChange(e) {
this.setState({
[e.target.id]: e.target.value
})
}
或者我们可以先创建该对象,然后将该对象传递给 setState
函数,如下所示:
Or we can create that object first, then pass that object to setState
function, like this:
onChange(e) {
let obj = {};
obj[e.target.id] = e.target.value
this.setState(obj);
}
您也不需要 prevState
.你可以直接用新值更新状态变量.prevState
仅当新状态值依赖于以前的状态值时才需要,比如在计数器的情况下.
Also you don't need the prevState
. You can directly update the state variable with new value.prevState
is required only when new state value is dependent on previous state value, like in case of counter.
这篇关于使用动态键对 setState 做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!