我的反应状态存储:
npm
我想更新该状态。所以我
permissionValue: [{user_id: 1, landing: true, skadi: true, heimdall: true, register: true, …}]
但是在设置数据期间读取handleChangePermissions = evt => {
console.log(this.state.permissionValue); //I can see the initial state
console.log("id: " + evt.target.id); //Thats the proper key
console.log("checked: " + evt.target.checked); //Thats the proper value
var data = this.state.permissionValue[0]; //I store the content of the array in data
console.log("data1");
console.log(data); //I can see the array data
data.evt.target.id = evt.target.checked; //I set the data , supposedly, but I receive " Cannot read property 'target' of undefined "
//Crashes
console.log("data2");
console.log(data);
console.log("----");
this.setState({
permissionValue: data
});
};
时,它会崩溃。有什么问题吗?
答案 0 :(得分:0)
一个原因可能是使用 onChange = {this.handleChange()} 调用变更处理程序 。在这种情况下,只需将函数作为值传递给onChange而不调用它。
onChange={this.handleChange}
或者尝试传递事件对象,例如
onChange={(e) => handleChange(e)}
答案 1 :(得分:0)
请勿在useState挂钩或this.setState之外修改状态。
由于概念,这行是一个问题,即按引用传递还是按值传递。
data.evt.target.id = evt.target.checked
您需要做的是复制状态并在那里进行更改。然后进行更改。
this.setState({
permissionValue: {
...data,
evt: {
...data.evt,
target: {
...data.evt.target,
id: evt.target.checked,
}
}
}
});
答案 2 :(得分:0)
var data = {... this.state.permissionValue [0]}
答案 3 :(得分:0)
已解决
handleChangePermissions = (evt) => {
console.log(this.state.permissionValue)
console.log("id: " + evt.target.id)
var idu = evt.target.id;
var checked = evt.target.checked
console.log("checked: " + evt.target.checked)
var data = this.state.permissionValue[0];
console.log("data1")
console.log(data)
data[idu] = checked;
console.log("data2")
console.log(data)
this.setState({
permissionValue: [data]
})
}