简体   繁体   English

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

[英]How can I update this.state with a method?

I'm trying to set new values to a state, but I can't do this with the methods, the state stills the same.我正在尝试为状态设置新值,但我无法使用这些方法执行此操作,状态仍然相同。

here a declare my state在这里宣布我的状态

 this.state = {
    notes: [],
    selected: null
    };
}

using componentDidMount I can update the state使用 componentDidMount 我可以更新状态

  componentDidMount() {
this.setState({
  notes: this.service.notes,
  selected: {
       title: "vazio",
       text: "vazio"
     }
    });
  }

but when I use this methods to update, the state stills the same但是当我使用这种方法更新时,状态仍然相同

  onSelect(note) {
   this.setState({
   selected: note
    });
  }

Have you tried?你有没有尝试过?

onSelect = note => {
  this.setState({
  selected: note
 });
}

This gives the onSelect property access to the component scope这使 onSelect 属性可以访问组件范围

Try尝试

onSelect = (note) => () => {
   this.setState({
      selected: note
   })
}

It builds a callback function, providing note as an argument它构建了一个回调函数,提供note作为参数

Use it as follows使用方法如下

onSelect={onSelect(note)}

On whatever handler you are using在您使用的任何处理程序上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM