我有一个简单的反应应用程序,它有一个登录,它在成功的身份验证时接收一个 Json Web 令牌,并将其传递给一个兄弟组件(成员),该组件在其 componentDidMount 中使用这个 JWT 对服务器进行 fetch 调用。问题是 componentDidMount 被调用了两次,第一次使用未定义的 JWT,第二次使用检索到的 JWT。这是我的代码:
应用程序(父代码):
class App extends Component{
state = {
clientToken: ''
}
callbackGetToken = (token) => {
this.setState({clientToken: token});
}
render(){
return(
<Switch>
<Route exact path="/" component={props => <Login sendToken = {this.callbackGetToken}/>}/>
<Route exact path="/members" component={props => <Members authToken = {this.state.clientToken}/>}/>
</Switch>
)
}
};
export default App;
登录组件:
class Login extends Component {
state = {
credentials:{
"username": "",
"password": ""
},
clientToken: ""
}
constructor(props){
super(props);
this.handleUsernameChange = this.handleUsernameChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
handleUsernameChange(event){
this.state.credentials.username = event.target.value;
}
handlePasswordChange(event){
this.state.credentials.password = event.target.value;
}
handleFormSubmit(event){
event.preventDefault();
const data = JSON.stringify(this.state.credentials);
fetch(loginFormurl, {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: data,
})
.then((response) => {
if(response.ok){
const token = response.headers.get('Authorization');
console.log(token);
this.setState({clientToken: token});
this.props.sendToken(token);
}else{
console.log(response.statusText);
}
})
.catch(function(error) {
console.log(error);
});
}
render() {
if (this.state.clientToken !== "") {
return <Redirect to='./members' />;
}
return (
<div className="App">
<h1 className="Login-title">Login to Social Media Aggregator</h1>
<form className="Login-box" onSubmit={this.handleFormSubmit}>
<p>
<label>
Username
<input id="username" type="text" name="username" required onChange={this.handleUsernameChange}/>
</label>
</p>
<p>
<label>
Password
<input id="password" type="password" name="password" autoComplete="password" required onChange={this.handlePasswordChange}/>
</label>
</p>
<p><input type="submit" value="Login"/></p>
</form>
</div>
);
}
}
export default withRouter(Login);
和兄弟成员组件:
class Members extends Component{
constructor(props){
super(props);
this.state = {
interrests: [],
authToken: props.authToken
}
}
componentDidMount(){
fetch(interestUrl, {
method: 'GET',
headers: {
"Content-Type": "application/json",
"Authorization": this.state.authToken
}
})
.then((response) => {
if(response.ok){
console.log(response.json());
}else{
console.log(response.statusText);
}
})
};
render(){
return(
<div>
<Menu/>
<Main/>
</div>
)
}
}
export default Members;
关于如何解决这个问题的任何想法?谢谢!
更新:
发现了问题。Login中的Redirect组件似乎两次创建了Members组件。如果我从页面中删除重定向,而只是放置一个链接来进行重定向,它会按预期呈现一次。不过,不知道如何解决这个问题:(