【发布时间】:2019-05-20 08:55:28
【问题描述】:
我有一个反应应用程序,在登录方法中它应该重定向到 /profile 路由。路径正在更改,但 Profile 组件未呈现。我认为这可能与路线的顺序或是否使用确切的路径有关。我尝试过使用和来自 react-router-dom。刷新页面有效,但将当前用户注销。链接来自导航栏而不是 this.props.history.push(/profile)。谢谢!
class App extends Component {
constructor(props){
super(props)
this.state = {
currentUser: null,
loggedIn: false,
unauthorizedUser: false
}
this.handleLoginSubmit = this.handleLoginSubmit.bind(this);
}
async handleLoginSubmit(e) {
e.preventDefault()
const url = 'http://localhost:3000/auth/login';
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: e.target[0].value,
password: e.target[1].value
})
}
await fetch(url, options)
.then(res => res.status === 200 ? res.json() : "Unauthorized")
.then(payload => {
if (payload !== "Unauthorized") {
window.localStorage.setItem("token", payload.token)
this.setState({ loggedIn: true,
currentUser: payload.user.id,
unauthorizedUser: false,
userfirstName: payload.user.firstName,
userlastName: payload.user.lastName
});
console.log('current user is ' + this.state.currentUser)
this.props.history.push(`/profile`);
} else {
this.setState({ loggedIn: false, unauthorizedUser: true })
}
})
.catch(err => {
console.log(err);
})
}
render() {
return (
<div className="App">
<Router>
<div>
<Nav loggedIn={this.state.loggedIn} handleLogout={this.handleLogout}/>
<Route exact path='/profile' render={props => <Profile {...props} currentUser={this.state.currentUser} firstName={this.state.userfirstName} lastName={this.state.userlastName}/>} />
<Route exact path='/' render={props => <HomePage {...props} handleLoginSubmit={this.handleLoginSubmit}
handleSignUpSubmit={this.handleSignUpSubmit} unauthorizedUser = {this.state.unauthorizedUser} signUpError = {this.state.signUpError}
loggedIn={this.state.loggedIn}/>}/>
<Route exact path='/update' render={props => <UpdateUser {...props} currentUser={this.state.currentUser}/> }/>
<Route exact path='/createoutfit' render={props => <AddOutfit {...props} currentUser={this.state.currentUser}/> }/>
<Route exact path='/items' component={Items} />
<Route exact path='/items/new' render={props => <AddItem {...props} currentUser={this.state.currentUser}/> } />
<Route exact path='/outfits' render={props => <Outfit {...props} currentUser={this.state.currentUser}/> }/>
<Route exact path='/add/itemstoOutfit' render={props => <AddItemsToOutfit {...props} currentUser={this.state.currentUser}/> }/>
<Route exact path='/items/upload' component={FileUpload}/>
</div>
</Router>
</div>
);
}
}
export default withRouter(App);
【问题讨论】:
-
请显示配置文件组件代码
标签: reactjs react-router