[英]How to test state update and component rerender after async call in react
[英]React Context API does not update state after async call
我正在為自己的代碼使用此示例 ,但是單擊按鈕后異步獲取調用后狀態不會更新。
這是一個真正簡單的應用程序,當用戶加載頁面時,它也會同時加載componentDidMount()
的狀態。 當用戶單擊“ 獲取”笑話”按鈕時,它將使用新的“笑話”再次設置狀態。
頁面加載后,笑話會在幾毫秒后得到很好的呈現。 但是,當單擊按鈕時,它僅在控制台中顯示獲取的“笑話”,但狀態為null
。
單擊按鈕時,我記錄了this
對象,它看起來像這樣,對嗎?
這是代碼和應用程序的“正常運行”: https : //codesandbox.io/s/friendly-shirley-qupr4
我感謝任何評論。
所以您忘記了綁定動作。 在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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.