在一类反应的js异步函数

问题描述 投票:0回答:2

我现在有一个叫做resetThenSet像这样功能

resetThenSet = (id, arrayId, title) => {
  let size = [...this.state[arrayId]]
  blah blah blah
}

这resetthenSet方法是从我的渲染方法被称为像这样:

        <Dropdown
          title="Size"
          arrayId="selectProduct"
          list={this.state.selectProduct}
          resetThenSet={this.resetThenSet}
        />

一切正常。我需要使用异步才能够有有等待里面的另一种方法。所以我切换resetThenset这样:

async resetThenSet(id, arrayId, title){
  let size = [...this.state[arrayId]]
  //blah blah blah
}

这使我在我的控制台错误。

Invalid argument passed as callback. Expected a function. Instead received: [object Promise]

这似乎是东西,所以我想我只想补充它结合相关的范围:

this.resetThenSet = resetThenSet.bind(this);

这给我的错误

resetThenSet is not defined

有一个简单的方法来改变脂肪箭头功能是在反应的异步功能?

我检查了这一点,它并没有帮助:How can I use async/await in a es6 javascript class?

reactjs
2个回答
1
投票
this.resetThenSet = this.resetThenSet.bind(this);

试试这个,因为你被绑定到一个未申报的功能。这就是为什么它被扔错误

你可以阅读更多关于“为什么函数绑定到这个” https://medium.freecodecamp.org/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb


1
投票
class youDidntTellUs extends Component {

async resetThenSet(id, arrayId, title){
let size = [...this.state[arrayId]]
  //blah blah blah
}

render(){
return (
  <Dropdown
      title="Size"
      arrayId="selectProduct"
      list={this.state.selectProduct}
      resetThenSet={() => this.resetThenSet()}
    />
...
© www.soinside.com 2019 - 2024. All rights reserved.