2017-04-01 160 views
0

我想关闭一个模式,当用户按下莫塔尔元素之外。不知何故,当调用Dismiss()时,回调中的状态仍然相同。为什么setState返回undefined?

这是怎么发生的?

export default class Message extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      id: "", 
      show: false 
     }; 
    } 

    componentDidMount() { 
     this.props.onRef(this); 
    } 

    Show(id) { 
     this.setState({ 
      id: id, 
      show: true 
     }); 
    } 

    Dismiss() { 
     this.setState({ 
      id: '', 
      show: false 
     }, function (state) { 
      console.log(state) // undefined 
     }); 
    } 

    render() { 
     if (this.state.show) { 
      return (
       <Modal close={() => this.Dismiss()}> 
        <h1>{this.state.id}</h1> 
       </Modal> 
      ); 
     } else { 
      return null 
     } 
    } 
} 

回答

6

不知道为什么会出现在你的回调状态的说法,应该只是

Dismiss() { 
    this.setState({ 
     id: '', 
     show: false 
    }, function() { 
     console.log(this.state) 
    }); 
} 
-2

是的,这是因为在this.setState功能REACT为async。而新的状态只在event queue

这里提供的是什么我的意思是:

this.setState({newAdded: "test"}); 
let youCannotGetIt = this.state.newAdded; // here is undefined, because this.setSate is async 
相关问题