我可以像下面这样创建动态状态:
constructor(props) {
super(props);
this.state = {};
}使用此方法创建状态:
func(name){
this.state[name];
}并使用以下内容进行setState:
func2(name,value){
this.setState({[name]:value});
}所以有了
this.func('color');
this.func('size');我有this.func.color和this.func.size。对吗?
它起作用了。
但我想要这样的东西。我想在'names'状态中创建所有新的动态状态。
constructor(props) {
super(props);
this.state = {names:[]};
}names是一种正常状态。
func(name){
this.state.names[name];
}
func2(name,value){
this.setState({names:{[name]:value}:});
}我调用这个函数:
func('color');
func('size');
func2('color','red');
func2('size','larg');我对console.log(this.state.names)的期望是:
{color:'red',size:'larg'}但是我只得到了{size:'larg'} (第二个函数)
我哪里错了?
发布于 2019-05-10 02:42:48
当您再次调用this.setState时,将覆盖names的值。
你有效地做到了:
this.setState({ names: { color: 'red' }});
this.setState({ names: { size: 'large' }});考虑在func2中使用Object.assign(),以确保不会替换要添加属性的对象。
func2(name,value) {
this.setState({
names: Object.assign(this.state.names, {[name]: value})
});
}https://stackoverflow.com/questions/56065628
复制相似问题