【问题标题】:React - state won't updateReact - 状态不会更新
【发布时间】:2017-10-25 07:33:54
【问题描述】:

我正在构建小型反应应用程序,但我遇到了状态不会更新的奇怪情况。这是一个例子:

class App extends Component {

constructor() {
  super();

  this.state = {
    locale: 'de',
    countryList: [],
    fetchInProgress: true,
    serverError: {},
    person: {
      salutation: '',
      firstName: '',
      lastName: '',
      birthDate: '',
      nationality: '',
      address: '',
      zipCode: '',
      city: '',
      country: '',
      mobileNumber: '',
      email: '',
      correspondanceLanguage: '',
    }
  };
}

componentDidMount() {
  this.setState({
    fetchInProgress: false
  }),()=>console.log('State updated', this.state)
}

}

我也尝试过使用其他方法:

componentDidMount() {
  const temp = {...this.state};
  temp.fetchInProgress = false;
  this.setState(temp),()=>console.log('State updated', this.state)
}

componentDidMount() {
  const temp = {...this.state};
  temp['fetchInProgress'] = false;
  this.setState(temp),()=>console.log('State updated', this.state)
}

但永远不会更新状态。有什么帮助吗?

【问题讨论】:

    标签: reactjs state


    【解决方案1】:

    您的所有方法都有语法错误。请注意,setState() 具有以下格式:

    setState(updater, callback)
    

    updater 可以是函数或对象,callback 是函数。


    从您的初始方法开始:

    this.setState({
      fetchInProgress: false
    }),()=>console.log('State updated', this.state)
    

    应该是:

    this.setState({
      fetchInProgress: false
    },()=>console.log('State updated', this.state))
    

    其他代码是正确的,直到再次到达setState() 部分:

    this.setState(temp),()=>console.log('State updated', this.state)
    

    应该是:

    this.setState(temp,()=>console.log('State updated', this.state))
    

    【讨论】:

    • 谢谢你,克里斯! 4 只眼睛总是比 2 只好 :)
    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    相关资源
    最近更新 更多