我想创建这样的状态:
componentWillReceiveProps(nextProps) {
nextProps.columns.forEach((c) => {
const name = nextProps.columns[nextProps.columns.indexOf(c)];
this.setState({ `${name}`: (this.props.activeHeaders.indexOf(c) > -1) });
console.log(`${name}`);
});
}
我正在映射我的数组列,因此数组上的每个项目,我想将它们的状态设置为键,有可能的方法吗?
最佳答案
Is there a possible way?
是的,但是您尝试的方式不正确,不是在循环内调用 setState,而是首先准备一个包含所有键值的对象,然后将该对象传递给 setState。
像这样:
componentWillReceiveProps(nextProps) {
let obj = {};
nextProps.columns.forEach((c, i) => {
const name = nextProps.columns[nextProps.columns.indexOf(c)];
obj[name] = this.props.activeHeaders.indexOf(c) > -1;
});
this.setState(obj);
}
没明白这行的意思:
const name = nextProps.columns[nextProps.columns.indexOf(c)];
关于javascript - 使用变量引用创建 react 状态名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48297639/