gpt4 book ai didi

javascript - react 更新状态奇怪的行为

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

我目前正尝试通过子组件更新我的组件状态,但回调函数告诉我状态未更新。

方法(loadModuleContent)

export default class LayoutPage extends React.Component {
constructor() {
super();
this.startSession = this.startSession.bind(this);
this.loadModuleContent = this.loadModuleContent.bind(this);
this.state = {
content: undefined,
group: undefined,
title: undefined,
selectionIndex: undefined
}
}

static navigationOptions = {
header: null
};

loadModuleContent(_content, _title, _selectedIndex) {
console.log("Inserting index: " + _selectedIndex);
this.setState({
content: _content,
title: _title,
selectionIndex: _selectedIndex
}, console.log("State updated:" + this.state.selectionIndex));
}
...

控制台日志
enter image description here

最佳答案

您没有按照 setState 调用中的预期使用 callback。您传递的不是传递回调,而是传递立即评估的方法调用。将您的 setState 更改为此

  this.setState({
content: _content,
title: _title,
selectionIndex: _selectedIndex
}, () => console.log("State updated:" + this.state.selectionIndex));

如果你不使用 ES06,你已经在第二个参数中写出了函数。

关于javascript - react 更新状态奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45193329/

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