我试图通过使用这样的嵌套属性来组织我的状态:
this.state = {
someProperty: {
flag:true
}
}
但是像这样更新状态,
this.setState({ someProperty.flag: false });
是行不通的。怎样才能正确地做到这一点呢?
我试图通过使用这样的嵌套属性来组织我的状态:
this.state = {
someProperty: {
flag:true
}
}
但是像这样更新状态,
this.setState({ someProperty.flag: false });
是行不通的。怎样才能正确地做到这一点呢?
当前回答
我们使用Immer https://github.com/mweststrate/immer来处理这类问题。
只是在我们的一个组件中替换了这段代码
this.setState(prevState => ({
...prevState,
preferences: {
...prevState.preferences,
[key]: newValue
}
}));
用这个
import produce from 'immer';
this.setState(produce(draft => {
draft.preferences[key] = newValue;
}));
使用immer,您可以将您的状态作为“普通对象”处理。 神奇的事情发生在代理对象的幕后。
其他回答
你可以用对象展开来做这个 代码:
this.setState((state)=>({ someProperty:{...state.someProperty,flag:false}})
这将适用于更多嵌套的属性
根据框架的标准,不确定这在技术上是否正确,但有时您只是需要更新嵌套对象。这是我使用钩子的解决方案。
setInputState ({ ... inputState, [括号]:内务部[括号],[childKey]: });
我知道这是一个老问题,但仍然想分享我是如何做到这一点的。假设构造函数中的状态是这样的:
constructor(props) {
super(props);
this.state = {
loading: false,
user: {
email: ""
},
organization: {
name: ""
}
};
this.handleChange = this.handleChange.bind(this);
}
我的handleChange函数是这样的:
handleChange(e) {
const names = e.target.name.split(".");
const value = e.target.type === "checkbox" ? e.target.checked : e.target.value;
this.setState((state) => {
state[names[0]][names[1]] = value;
return {[names[0]]: state[names[0]]};
});
}
并确保你的输入相应的名称:
<input
type="text"
name="user.email"
onChange={this.handleChange}
value={this.state.user.firstName}
placeholder="Email Address"
/>
<input
type="text"
name="organization.name"
onChange={this.handleChange}
value={this.state.organization.name}
placeholder="Organization Name"
/>
尽管嵌套并不是处理组件状态的真正方式,但有时对于单层嵌套来说很容易。
对于这样一个州来说
state = {
contact: {
phone: '888-888-8888',
email: 'test@test.com'
}
address: {
street:''
},
occupation: {
}
}
我使用的一个可重用的方法是这样的。
handleChange = (obj) => e => {
let x = this.state[obj];
x[e.target.name] = e.target.value;
this.setState({ [obj]: x });
};
然后为你想要处理的每个嵌套传递obj名称…
<TextField
name="street"
onChange={handleChange('address')}
/>
There is another option and this works if there are multiple items in the list of objects: copy the object using this.state.Obj to a variable (say temp), use filter() method to traverse through the object and grab the particular element you want to change into one object(name it updateObj) and the remaining list of object into another object(name this as restObj). Now edit the contents of object you want to update creating a new item (say newItem). Then call this.setUpdate() and use spread operators to assing new list of objects to the parent object.
this.state = {someProperty: { flag:true, }}
var temp=[...this.state.someProperty]
var restObj = temp.filter((item) => item.flag !== true);
var updateObj = temp.filter((item) => item.flag === true);
var newItem = {
flag: false
};
this.setState({ someProperty: [...restObj, newItem] });