【发布时间】:2020-10-26 12:54:25
【问题描述】:
我正在尝试创建一个简单的身份验证,但显示的内容有些问题。在 componentDidMount 中,我获取有关当前用户的信息,然后将其传递给标题,在 if 语句中确定状态“页面”。使用“changePage”,我在登录或注销后更改此状态。 但是我在 Header 中的 if 语句无法正常工作:登录后显示注销,但刷新页面后显示登录,尽管 this.props.currentUser 存在
编辑: 添加了一些带有“this.props.currentUser”的console.log,当我登录时: console log Header:23 in ComponentDidMount 所以从 Main 传递我的 currentUser 有一些问题
Main.js
class App extends React.Component {
constructor(){
super();
this.state = {
currentUser: null,
}
this.updateCurrentUser = this.updateCurrentUser.bind(this);
}
componentDidMount(){
let that = this
axios.get('http://localhost:3000/isUser',{
})
.then(function(response){
console.log(response.data.email)
if(response.data.email){
that.setState({
currentUser: response.data.email
})
} else {
that.setState({
currentUser: null
})
}
})
.catch(function(error){
console.log(error);
})
}
updateCurrentUser(email) {
this.setState({
currentUser: email
})
}
render(){
return <Header updateCurrentUser={this.updateCurrentUser} token = {this.props.ids.token} currentUser = {this.state.currentUser}/>
}
}
Header.js
class Header extends React.Component {
constructor(props){
super(props);
if (this.props.currentUser == null){
this.state = {
page:"login"
}
} else{
this.state = {
page: "delete"
}
}
this.changePage = this.changePage.bind(this);
}
changePage(newPage) {
this.setState({
page: newPage
})
}
render() {
switch(this.state.page) {
case "signup":
return <Signup changePage={this.changePage} updateCurrentUser={this.props.updateCurrentUser} token = {this.props.token} currentUser = {this.props.currentUser}/>
case "login":
return <Login changePage={this.changePage} updateCurrentUser={this.props.updateCurrentUser}token = {this.props.token} currentUser = {this.props.currentUser}/>
case "delete":
return <Logout changePage={this.changePage} updateCurrentUser={this.props.updateCurrentUser} token = {this.props.token} currentUser = {this.props.currentUser} />
}}}
【问题讨论】:
-
嗨@Melon8991 是否可以显示 Main 和 Header 组件的整个代码?或者至少尝试将代码提取到显示 pronlem 是什么的最低限度
-
您不能直接设置状态:this.state = { page:"login" } 应该像这样用 setState 函数替换任何地方:this.setState({ page:"login" });跨度>
-
@charly1212 它不起作用,我什至试图在 componentDidMount 中使用我的 if 语句和 setState。还有我在controllet中的this.state,应该没问题吧?
-
@RicardoSanchez 添加了整个代码
-
Header 组件上的 state 设置不正确
标签: reactjs