我知道我可以简单地一次性添加属性。 this.state={a:'1','b':2}
。但是,如果我们想向 state
对象添加额外的属性,而不仅仅是在 constructor
中,或者如果需要在条件下添加属性,该怎么办。
它是否只适用于固定数字或属性? (我知道 dictionary
和 arrays
是 state
的元素。)
constructor(){
super();
this.state = { item: 'first item' }
this.state = { item2: 'second item' } // Or += append are not accepted.
}
显然,React state
是一个 JS 对象
所以,this.state.item2= 'new item';
有效。
由 Andy Ray
和 Mark E
在下面的评论中回答。问题的另一部分:如何动态创建状态由
原因
并将其标记为已回答
谢谢大家
最佳答案
您可以拥有像这样的动态状态:
class DynamicStateBasedOnProps extends React.Component{
constructor(props){
super();
this.state = { static: 'I am static' };
}
componentDidMount(){
const stateBasedOnProps = Object.keys(this.props)
.map(key => ({[key]: this.props[key]}));
this.setState(dynamicState)
}
render() {
return <div>
{JSON.stringify(this.state)}
</div>;
}
}
关于javascript - 如何在 react 中创建更多状态? react 状态的属性数量是否固定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51343800/