【问题标题】:Why is my state undefined?为什么我的状态未定义?
【发布时间】:2017-04-07 07:40:32
【问题描述】:

尝试在 React 中遵循一个简单的时钟/倒计时教程:

constructor(props) {
    super(props);
    this.state = {
      secondsRemaining: 10
    };
  }

  componentDidMount(){
    let interval = setInterval(this.timer, 1000);
    this.setState({ secondsRemaining: this.state.secondsRemaining })
    this.setState({ interval: interval });
  };

  componentWillUnmount() {
    clearInterval(this.state.interval);
  };

  timer(){
    this.setState({ secondsRemaining: this.state.secondsRemaining -1 });
  };

很明显,一切都在做什么,但是当我运行它时,我在计时器函数中收到一条错误消息 cannot read property secondsRemaining of undefined

这可能是我错过了一些愚蠢的东西,但我只是看不到它

关注了这个问题的答案:setInterval in a React app

【问题讨论】:

  • this.timer.bind(this)

标签: javascript reactjs


【解决方案1】:

myfunction.bind() 方法指定 this 在被调用时将在方法内部引用的内容。为确保当您调用 this.timer() 时,您实际上是在引用组件状态而不是调用它的对象,您必须传递 this.timer.bind(this)

【讨论】:

    【解决方案2】:

    因为 setInterval 会调用 this.timer 而 this 会是 window 对象。 你可以使用闭包:

    componentDidMount(){
       let currentInstance = this;
       let interval = setInterval(function(){ currentInstance.timer(); }, 1000);
       ...
    };
    

    在执行方法 componentDidMount 时,将其上下文与初始化的属性状态,保存到变量 currentInstance 中。 然后我们将 currentInstance 的值封闭到 setInterval 第一个参数中。

    【讨论】:

      【解决方案3】:

      timer 定义为Arrow Function

        timer() => this.setState({ secondsRemaining: this.state.secondsRemaining -1 })
      

      .bind 你的方法在constructor:

      constructor(props) {
          super(props);
          this.state = {
            secondsRemaining: 10
          };
          this.timer = this.timer.bind(this);
      }
      

      我不推荐在render 内使用this.timer.bind(this);因为这样做,.bind 将在每次渲染时创建一个新函数。

      【讨论】:

        【解决方案4】:

        因为你的边界上下文。您可以使用箭头函数或 this.timer.bind(this)

        【讨论】:

          猜你喜欢
          • 2021-12-16
          • 1970-01-01
          • 2016-10-27
          • 2017-02-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多