【发布时间】:2019-08-04 01:39:26
【问题描述】:
我正在尝试使用此处显示的反应路由器身份验证重定向 (https://reacttraining.com/react-router/web/example/auth-workflow),但我遇到了很多问题。我目前收到一个错误:无法读取未定义的属性“状态”。我无法弄清楚我做错了什么。任何帮助将不胜感激。另外,我很想听听您对我的代码的任何注释/改进(这是我使用 React 的时间)。
错误来自 Login 类渲染函数中的 {from} 这是codeandbox的链接,它有更完整的代码:https://codesandbox.io/embed/bold-mendel-hgvun
`const auth = {
isAuthenticated: false,
authenticate(callback) {
this.isAuthenticated = true;
setTimeout(callback, 30000);
},
signout(callback) {
this.isAuthenticated = false;
setTimeout(callback, 30000);
}
};
//Class Login:
handleSubmit(event){
event.preventDefault();
var payload = {
"email": this.state.email,
"password": this.state.password
}
axios.post({url}"/login", payload)
.then((res) => {
console.log(res);
if (res.data.status == "success") {
auth.authenticate(() => {
this.setState({ redirectToReferrer: true});
});
this.setState({authenticated: true});
this.setState({token: res.data.data.token})
}
}
render() {
let {from} = this.props.location.state || {from: {pathname: '/'}};
const { redirectToReferrer } = this.state;
if (redirectToReferrer == true) {
return <Redirect to={from} />
}
return (
<form>
<input value={this.state.email} onChange={this.handleChange} type="email" name="email" placeholder="Email" />
<input value={this.state.password} onChange={this.handleChange} type="password" name="password" placeholder="Password" />
<button type="submit" onClick={this.handleSubmit} className="btn btn-primary">Login</button>
</form>
);
}
}
const PrivateRoute = ({ component: Component, authed, ...rest }) => (
<Route {...rest} render={(props) => (
authed === true
? <Component {...props} />
: <Redirect to={{
pathname: '/login',
state: { from: props.location }
}} />
)} />
);
//called in class App like this
render() {
const {authenticated}=this.state;
return(
<React.Fragment className='root'>
<Router>
<Switch>
<Route path="/login" render={() => <Login callbackToParent={this.loginCallback} /> }exact/>
<Route path="/register" render={() => <Register callbackFromParent={this.registerCallback} /> } exact/>
<PrivateRoute authed={authenticated} path="/" render={() => <Home tokenFromParent={this.state.token} /> } exact/>
</Switch>
</Router>
</React.Fragment>
);`
【问题讨论】:
-
handleSubmit 函数有效吗??我不觉得网址不对??
-
函数表达式 PrivateRoute 声明在哪里? (哪个文件)
-
您的路由器配置正确了吗?状态未定义可能是因为组件没有从反应路由器接收到道具“状态”。您能否分享来自codesandbox.io 或jsbin.com 的完整代码
-
这里是codeandbox的链接:codesandbox.io/embed/bold-mendel-hgvun
标签: reactjs react-router