Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ComponentDidMount中调用的setState未更新状态?_Javascript_Reactjs_React Native - Fatal编程技术网

Javascript ComponentDidMount中调用的setState未更新状态?

Javascript ComponentDidMount中调用的setState未更新状态?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我不熟悉react native,我在这里尝试在加载组件时更新状态。但是,状态没有更新 constructor(props) { super(props); this.state = { selectedSection: 'None', sectionObject: { index: 0, key: ''}, sectionIndex: 0, sectionArray: [], }; } componentDidMount() { this.setState({ section

我不熟悉react native,我在这里尝试在加载组件时更新状态。但是,状态没有更新

constructor(props) {
super(props);

this.state = {
 selectedSection: 'None',
 sectionObject: { index: 0, key: ''},
 sectionIndex: 0,
 sectionArray: [],
 };
}

componentDidMount()
{
 this.setState({
 sectionObject: { index: this.state.sectionIndex, key: this.state.selectedSection},
 sectionArray: this.state.sectionArray.concat(this.state.sectionObject),
 })
 console.log('sectionObject:',this.state.sectionObject);
 console.log('section array:',this.state.sectionArray);
}

我做错了什么?

更新

componentDidMount更新状态,但这是一个异步的,所以我认为您可以在render中看到更新状态

类Hello扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
selectedSection:“无”,
sectionObject:{索引:0,键:''},
分区索引:0,
sectionArray:[],
};
}
componentDidMount(){
这是我的国家({
selectedSection:“wowowowowo”,
})
}
render(){
console.log(this.state.selectedSection)
返回{this.state.selectedSection}
}
}
ReactDOM.render(
,
document.getElementById('容器')
);

尝试登录时,可以看到旧值。尝试像这样登录setState回调
这个setState({key:value},()=>console.log(this.state))。
看看这个:

您如何知道状态未更新?你在做日志记录吗?@Prakashsharma,是的
setState
是异步的<代码>控制台。日志
设置状态
之后将显示旧状态。使用
setState
callback。你能告诉我在那些控制台语句中得到的值是什么吗?你需要像这样检查日志:
this.setState({},()=>{console.log(this.state)})
componentDidMount(){this.setState(prevState=>({sectionObject:{…prevState.sectionObject,索引:this.state.sectionIndex,键:this.state.selectedSection}}),()=>{console.log('sectionObject:',this.state.sectionObject);}嘿,我在这里提供了解决方案!!使用setState的函数形式总是很好的。在我的例子中,我使用prevState作为参数和道具作为参考。记住,setState调用是异步的。在你的例子中,你在setState执行完成之前在控制台日志中打印状态。因此,如果你是打印它时,您可能不会得到当前值。相反,您总是会得到以前的状态值。因此,setState的函数形式在控制台中打印状态值时,除了另外一个参数。