2017-07-19 52 views
1

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

方法(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)); 
    } 
... 

您没有使用callback按预期在setState调用控制台日志
enter image description here

回答

2

。不是传递回调,而是传递一个方法调用,该调用立即进行评估。更改setState

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

如果你不使用你ES06在第二个PARAM写出来的功能。

+0

感觉很蠢....谢谢 –