gpt4 book ai didi

javascript - 如何在 react 中创建更多状态? react 状态的属性数量是否固定?

转载 作者:行者123 更新时间:2023-11-30 14:30:03 25 4
gpt4 key购买 nike

我知道我可以简单地一次性添加属性。 this.state={a:'1','b':2} 。但是,如果我们想向 state 对象添加额外的属性,而不仅仅是在 constructor 中,或者如果需要在条件下添加属性,该怎么办。

它是否只适用于固定数字或属性? (我知道 dictionaryarraysstate 的元素。)

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 RayMark 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com