React类:setState什么都不做(并且没有报告错误)

时间:2017-09-22 05:18:56

标签: javascript reactjs setstate

我有一个带有这个构造函数的React类:

handleSubmit(e) {
e.preventDefault(); // this prevents the page from reloading -- do not     delete this line!

// Implement the rest of this function here!
alert('this.state.hidden: ' + this.state.hidden);
if (this.state.hidden == true){
  alert('setting hidden to false');
  this.setState({hidden: false});
  }
  else{
    alert('setting hidden to true');
    this.setState({hidden: true});
  }
alert('this.state.hidden: ' + this.state.hidden);
    . . . 

My problem is that neither this.setState({hidden: false);
nor                        this.setState({hidden: 'false'); 

然后我有这个功能:

{{1}}

改变状态! 警告'框确认通过代码的路径,并且只有'setState'似乎是NOP!

2 个答案:

答案 0 :(得分:2)

setState是异步的,因此您之后无法看到更新。这就是为什么您在上次alert来电时看不到最新价值的原因。

有关更多信息,请查看ReactJs的文档: https://facebook.github.io/react/docs/state-and-lifecycle.html#using-state-correctly

我根据你的代码编写了一个示例代码:



class AddList extends React.Component {
  constructor(props) {
    super(props)
    
    this.state = { hidden: true }
    
    this.handleSubmit = this.handleSubmit.bind(this)
  }
  
  handleSubmit(event) {
    event.preventDefault()
    
    this.setState({ hidden: !this.state.hidden })
  }
  
  render() {
    return (
      <div>
        <div>State value: {this.state.hidden ? 'hidden' : 'visible'}</div>
        <button onClick={this.handleSubmit}>Click-me</button>
      </div>
    )
  }
 }
 
 ReactDOM.render(<AddList />, document.getElementById('root'))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

如果要在更新后读取状态值,可以使用setState方法的第二个参数,它是一个回调函数。在更新状态并重新呈现组件之后执行此回调函数。对于前者 function scrollToTop(){ setTimeout(function(){ $('html, body').animate({scrollTop:0}, { duration: 4000, complete: function(){ scrollToBottom(); } }); },10000); } function scrollToBottom(){ setTimeout(function(){ $('html, body').animate({scrollTop:$(document).height()}, { duration: 4000, complete: function(){ scrollToTop(); } }); },10000); } scrollToBottom();