【发布时间】:2019-12-25 06:07:33
【问题描述】:
我正在尝试使用此处显示的反应路由器身份验证重定向 (https://reacttraining.com/react-router/web/example/auth-workflow)。我目前收到错误无法接收未定义的属性“状态”。
错误出现在我的登录组件中,该组件当前在 React Router 中通过 Route path="/login" render={() => Login } exact 调用。但是当我将它更改为Route path="/login" component={Login} exact 时,它会呈现并且不会给我错误。我确实需要使用渲染函数,因为我需要它来进行回调。关于它为何如此行事的任何想法。
function Protected() {
return <h3>Protected</h3>;
}
function AuthExample() {
return (
<React.Fragment>
<Router>
<Switch>
<Route path="/login" component={Login} exact />
<PrivateRoute path="/" render={() => <Protected />} exact />
</Switch>
</Router>
</React.Fragment>
);
}
class Login extends Component {
constructor(props) {
super(props);
this.state = {
redirectToReferrer: false,
};
}
handleSubmit(event) {
fakeAuth.authenticate(() => {
this.setState({ redirectToReferrer: true });
});
}
render() {
const { from } = this.props.location.state || { from: { pathname: "/" } };
const { redirectToReferrer } = this.state;
if (redirectToReferrer === true) {
this.props.history.push(from.pathname);
}
return (
<button
type="submit"
onClick={this.handleSubmit}
className="btn btn-primary"
>
Login
</button>
);
}
}
我还直接从上面提供的链接中获取了 fakeAuth 和 PrivateRoute。这是代码框的链接:https://codesandbox.io/s/dawn-cherry-3yv8e?fontsize=14。 当我单击登录时,作为一种附带任务,它不会将我重定向到受保护的页面。感谢您的帮助。
【问题讨论】:
标签: reactjs authentication react-router-dom