因此,我目前面臨一個常見問題,即我的類組件中的狀態值不會立即更改,而是僅在呈現/重繪 頁面后才更改。我有一個名為“auth”的狀態,我想在單擊“注銷”時將其屬性值設為 false。當用戶按下“注銷”按鈕時,我想立即將身份驗證狀態設定為“假”,然后將它們重定向到登錄頁面。但我的問題是 this.state.auth 如果沒有重繪 /重新渲染發生仍然是真的。請記住,它必須在類組件中作業,如下所示。
import React, { Component, useEffect, useState} from 'react';
import { AuthContext } from '../Context/AuthContext';
class Home extends Component {
state = {
auth: true
}
handleLogOut = () => {
localStorage.clear();
sessionStorage.clear();
this.setState({auth: false}); //Here it stays 'true' up until refresh ?
this.props.history.push('/');
}
render() {
return (
<AuthContext.Provider value={this.state.auth}>
<div>
<button onClick = {this.handleLogOut}>Log out</button>
</div>
</AuthContext.Provider>
);
}
};
export default withRouter(Home);
uj5u.com熱心網友回復:
在您的特定情況下,請使用componentDidUpdate.
你可以這樣使用它
componentDidUpdate(prevProps, prevState) {
console.log(this.state) // Logs new state.
}
但是,我建議您轉向功能組件,因為componentDidUpdate類似的基于類的組件被視為遺留組件。
資源
uj5u.com熱心網友回復:
this.setState(
{ auth: false },
() => this.props.history.push("/")
);
uj5u.com熱心網友回復:
我在這里為您創建了一個小沙盒演示:https : //codesandbox.io/s/a-simple-react-router-v4-tutorial-forked-uznym
您的 handleLogOut 函式會將 auth 讀取為 false,直到 React 重新呈現組件。除非可能發生任何錯誤,否則您可以在渲染方法中記錄狀態并查看它在那里讀取的內容。
handleLogOut = () => {
console.log(this.state.auth);
localStorage.clear();
sessionStorage.clear();
this.setState({ auth: false }); //Here it stays 'true' up until refresh ?
// this.props.history.push("/");
console.log(this.state.auth);
};
render() {
console.log(this.state.auth);
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360491.html
標籤:javascript 反应 使用状态 网络前端
下一篇:Map()回傳重復的組件
