javascript - 在 componentDidMount 中设置状态

标签 javascript reactjs branch.io

我正在尝试等待 componentDidMount 中的数据然后改变我的状态isLoading为 false 但setState没有触发。我能够 console.log branch.init 内的数据但我不知道为什么setState不工作。

    state = {
      isLoading: true,
    }

    componentDidMount() {
      console.log("componentDidMount");

      let branchKeyTest = 'key_test_aBcDeF'

      branch.init(branchKeyTest, function(err, data) {
        console.log(JSON.stringify(data, null, 1))

        this.setState({ isLoading: false })

        if (data && data.data_parsed) {
          switch (data.data_parsed.link_type) {
            case 'new_release':
              localStorage.setItem('redirect', JSON.stringify({
                'link_type': 'new_release',
                'release_id': data.data_parsed.release_id
              }));
              break;
            default:
              console.log("do nothing")
          }
        }
      })
    }


  render() {
    const { isLoading } = this.state;
    if (!isLoading) {
      return (
        <div>Done Loading</div>
      )
    else {
      return (
        <div>Still Loading</div>
      )
    } 
  }

最佳答案

branch.init(branchKeyTest, function(err, data) { 需要更改为 branch.init(branchKeyTest, (err, data) => { 因为您无权访问匿名函数内类的 this 关键字。

按照您编写的方式,您无权访问 this,因为 this 引用的是函数的上下文 - 而不是类。通过将其更改为粗箭头语法,您可以访问 React 类的上下文的 this

您可以阅读有关 this here 的更多信息.

关于javascript - 在 componentDidMount 中设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59380682/

相关文章:

javascript - 在redux中发送action,如果switch中的reducer指令有多种情况

android - 使用 Branch 创建用户邀请码的正确方法是什么?

Android:使用 Branch.io 生成深层链接和 Google Invites 进行内容共享

javascript - 等待本地存储同步

javascript - 使用 rxJS 观察 dom 元素的大小调整

javascript - 有没有办法只在完整输入后才渲染?延迟 render() - ReactJS

ios - 如何查看iOS Branch SDK版本

php - 为什么谷歌地图代码阻止了我的其他 js 脚本?

javascript - RequireJS 对象未定义

javascript - 如何根据 Mongoose 中的对象ID列表删除数组项?