我想创建组件 - 以便只有授权用户才能访问它。我的想法是,在我的Login组件(这是一个子组件)中从后端接收到响应200之后,我会以某种方式使用authed:true作为父组件中的props。我理解这些说明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>
问题是我无法在我的子组件中将函数定义为prop。
这是我的父组件中应该被称为prop的函数。
setAuthToTrue=() => {
this.setState({authed:true})
}
但我从未到过这里。
这就是我在AuthExample(父)组件中定义路由路由器的方法 - 使用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
);
});
}
答案 0 :(得分:0)
我建议你尝试添加调试器 react-router-with-props / PrivateRoute.js in 反应路由器与 - 道具/ renderMergedProps.js
并检查您的道具是否实际上正确传递。
他正在做很简单的工作,要么允许反应来渲染你的组件,要么重定向到作为prop提供的url。
我建议您使用HigherOrderComponents或OnEnter路由挂钩来处理这些情况,而不是第三方组件。