【问题标题】:React - setState in an observableReact - 可观察对象中的 setState
【发布时间】:2020-10-05 08:56:11
【问题描述】:

我有一个数组

    let exams = []
and an observable

    stream.subscribe(
       function onNext(patients) {
           let patient = patients[0]
           await exams.push({
               patient,
               session
           })
           // this.setState(exams)
       }, function onError(error) {
            console.log('error',error)
       }, function onComplete() {
           console.log("exams",exams)
       });

现在在onNext 函数中,我想调用setState。

在 observable 之后数组是空的,并且由于某种原因,setState 不能从 observable 内部调用。

【问题讨论】:

  • 常规函数和箭头函数之间的关键字this 是有区别的。大多数时候你会想要在 React 中使用箭头函数,这样你仍然可以访问组件的 this 上下文

标签: javascript reactjs observable kinvey


【解决方案1】:

关注former question:

let that = this
    stream.subscribe(
   function onNext(patients) {
       let patient = patients[0]
       await exams.push({
           patient,
           session
       })
       that.setState({exams})
   }, function onError(error) {
        console.log('error',error)
   }, function onComplete() {
       console.log("exams",exams)
   });

使用let that = this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-09
    • 2019-01-30
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 2017-07-12
    相关资源
    最近更新 更多