我正在做一個簡單的反應應用程序,我有一個App組件,它跟蹤狀態並呈現它。起初狀態它是一個空字符串。之後,當我訪問/ signin時,我點擊一個按鈕,將狀態從「」更改爲「Marc」,並通過道具將其傳遞給在其頁面上呈現用戶名的Profile組件。問題是它不會改變狀態,它總是「」。我試圖調試,狀態總是「」,但實際調用setState方法。所以我不知道爲什麼。誰能幫我?在此先感謝,我附上了代碼。React setState沒有設置狀態
APP:
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
session: ""
};
this.updateUser = this.updateUser.bind(this);
}
updateUser() {
this.setState({
session: "Marc"
});
}
render() {
return(
<BrowserRouter>
<Switch>
<Route path exact='/' component={Home}/>
<Route path='/profile' render={(props) => (
<Profile session={this.state.session} />
)}/>
<Route path='/signin' render={(props) => (
<SignIn onClick={this.updateUser} />
)}/>
</Switch>
</BrowserRouter>
);
}
}
簽到:
export default class SignIn extends React.Component{
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
responseGoogle (googleUser) {
const mail = googleUser.profileObj.email;
const familyName = googleUser.profileObj.familyName;
const name = googleUser.profileObj.name;
//this.changeName(mail);
alert("Mail: " + mail + "\n" + "Nom i Cognoms: " + name + "\nSuccessfully Logged In");
}
handleClick() {
this.props.onClick();
}
render() {
return (
<div>
<GoogleLogin
clientId="CLIENTID"
onSuccess={this.responseGoogle}
onFailure={this.responseGoogle}
buttonText="Google"/>
<button onClick={this.handleClick}>Instant User</button>
</div>
);
}
}
簡介:
export default class Profile extends React.Component {
constructor(props) {
super(props)
}
render() {
return(
<h1>I am {this.props.session} User</h1>
);
}
}
只有當您更改路線時,配置文件組件纔會顯示道具,而我沒有看到您正在更改路線。您是否也在控制檯中看到一些錯誤 –
不,我在控制檯中看不到任何錯誤。所以當我點擊「登錄」頁面上的按鈕時,如果我想讓個人資料頁面更改用戶,我該怎麼辦? – marc1161
看到這個https://stackoverflow.com/questions/44127739/programatically-routing-based-on-a-condition-with-react-router/44128108#44128108 –