React native 反应本机-我可以设置动态初始状态吗?
假设我有这样一个状态:React native 反应本机-我可以设置动态初始状态吗?,react-native,React Native,假设我有这样一个状态: constructor(props) { super(props); this.state = { FirstTime: { foo: 'ex1' } } } constructor(props) { super(props); this.state = { FirstTime: { foo: 'ex1', bar: 'ex2' } } } 然后我设置state
constructor(props) {
super(props);
this.state = {
FirstTime:
{
foo: 'ex1'
}
}
}
constructor(props) {
super(props);
this.state = {
FirstTime:
{
foo: 'ex1',
bar: 'ex2'
}
}
}
然后我设置state
第一次添加另一个键/值:
this.setState({FirstTime: {...this.state.FirstTime, bar: 'ex2'}})
有一种方法可以将初始状态更改为如下所示:
constructor(props) {
super(props);
this.state = {
FirstTime:
{
foo: 'ex1'
}
}
}
constructor(props) {
super(props);
this.state = {
FirstTime:
{
foo: 'ex1',
bar: 'ex2'
}
}
}
当我重新加载应用程序时?试试这样的方法
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
第一次:{
foo:'ex1'
}
}
}
render(){
console.log(this.state.FirstTime);//很抱歉,在这一行中发现了一个拼写错误
返回(
嘿
);
}
componentDidMount(){
设obj={
酒吧:“ex2”
}
让finalData={…this.state.FirstTime,…obj}
this.setState({FirstTime:finalData})
}
}
const rootElement=document.getElementById(“根”)
ReactDOM.render(
,
根元素
)
创建另一个对象并将数据推入GetDerivedStateTrops/componentDidMount中的状态method@RaajNadar这是否意味着我需要将setState
放在componentDidMount
上?它将删除动态
我认为如果您能给我更多关于您试图实现的目标的信息,我可以提供其他解决方案。它应该可以做到这一点,但是如果我在componentDidMount()的开头添加console.log(this.state.FirstTime)
第一次仍然有一个键,这不是我想告诉你的,这只是一个技巧,使第一次
在渲染时有2个键,但是构造函数中的第一次
总是得到1个键
,因为构造函数运行一次!使用高阶组件然后bcuz构造函数是首先运行的东西,在构造函数之前我们不能做任何事情!