猿问

如何使用方法更新 this.state?

我正在尝试将新值设置为状态,但我无法使用方法执行此操作,状态仍然相同。


在这里宣布我的状态


 this.state = {

    notes: [],

    selected: null

    };

}

使用 componentDidMount 我可以更新状态


  componentDidMount() {

this.setState({

  notes: this.service.notes,

  selected: {

       title: "vazio",

       text: "vazio"

     }

    });

  }

但是当我使用这种方法更新时,状态仍然相同


  onSelect(note) {

   this.setState({

   selected: note

    });

  }


交互式爱情
浏览 82回答 2
2回答

杨魅力

你有没有尝试过?onSelect = note => {  this.setState({  selected: note });}这使 onSelect 属性可以访问组件范围

幕布斯7119047

尝试onSelect = (note) => () => {   this.setState({      selected: note   })}它构建一个回调函数,note作为参数提供如下使用它onSelect={onSelect(note)}在您使用的任何处理程序上
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答