我想创建组件 - - 以便只有授权用户才能访问它。这个想法是,在我的登录组件(这是一个子组件)中收到来自后端的响应 200 后,我会以某种方式使用 authed:true 作为父组件中的道具。我了解此说明https://reactjs.org/docs/lifting-state-up.html并且还在其他组件上使用了类似的程序。但是,在这种情况下,我收到了错误:
TypeError: this.props.authAfter200 is not a function
at Login.handleSetAuthAfterVerified200 (AuthExample.js:325)
at AuthExample.js:350
at <anonymous>
问题是我无法在我的子组件中将函数定义为道具。
这是我的父组件中应该作为道具调用的函数。
setAuthToTrue=() => {
this.setState({authed:true})
}
但我从来没有到过这里。
这就是我在 AuthExample(parent) 组件中定义路由路由器的方式 - 为此使用react-router-with-props:
<PrivateRoute
exact
path="/private"
redirectTo="/login"
component={DailyNewsForUOnly}
text="This is a private route"
authAfter200={this.setAuthToTrue}
authed={this.state.authed}
/>
这是我的子组件中的部分 - Login.js 我应该能够在我的道具上定义函数以传递给父组件 - 但我不能:
handleSetAuthAfterVerified200() {
//this.setState({authed:true})
this.props.authAfter200()
}
verifyToken() {
let request = {
method: "post",
url: "https://xxxxxx/xxxx/verify/",
data: {
user: this.state.email,
token: this.state.token
},
withCredentials: true
};
console.log("request to verify");
console.log(request);
this.setState({ requestInMotion: true });
axios(request)
.then(response => {
console.log("response from verify", response);
if (response.status === 200) {
this.handleSetAuthAfterVerified200()
this.setStateAfterVerified200()
}
})
.catch(error => {
console.log(error);
this.setState({ requestInMotion: false, validationState: "error" });
console.log(
"this.state in the error part of response in verify",
this.state
);
});
}