【问题标题】:React Context API does not update state after async call异步调用后 React Context API 不更新状态
【发布时间】:2019-06-14 13:46:33
【问题描述】:

我一直在关注this example 以获取我自己的代码,但在单击按钮时进行异步获取调用后状态不会更新。

这是一个真正简单的应用程序,当用户加载页面时,它也会加载componentDidMount() 中的状态。当用户点击 Get "joke" 按钮时,它会再次使用新的 "joke" 设置状态。

当页面加载时,笑话会在几毫秒后很好地呈现。但是当点击按钮时,它只在控制台中显示提取的“笑话”,但状态为null

单击按钮时,我记录了this 对象,它看起来像这样,对吗?

这是代码和“正在运行”的应用程序:https://codesandbox.io/s/friendly-shirley-qupr4

我很感激任何 cmets。

【问题讨论】:

    标签: javascript reactjs ecmascript-6 react-redux


    【解决方案1】:

    所以你忘记了绑定动作。 在 JokeStat.js 中

    中的绑定动作
            <JokesContext.Provider
                    value={{
                        joke: this.state.joke,
                        getJoke: this.getJoke.bind(this)
                    }}
                >
                    {this.props.children}
                </JokesContext.Provider>
    

    或者改变

        async getJoke() {
            console.log("get joked triggered");
            const joke = await fetchJoke();
            console.log(joke,'joke')
            console.log("state", this.state);
            this.setState({ joke });
        }
    

         getJoke = async() => {
            console.log("get joked triggered");
            const joke = await fetchJoke();
            console.log(joke,'joke')
            console.log("state", this.state);
            this.setState({ joke });
        }
    
    

    或第三个选项

         <JokesContext.Provider
             value={{
               joke: this.state.joke,
               getJoke: ()=>this.getJoke()
              }}
            >
               {this.props.children}
            </JokesContext.Provider>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多