gpt4 book ai didi

reactjs - React Router v4 在表单提交时重定向

转载 作者:行者123 更新时间:2023-12-03 13:15:31 25 4
gpt4 key购买 nike

全新 react ,点击“登录”页面上的提交后尝试重定向到“主页”。尝试遵循 react 路由器教程。

当我单击表单上的提交按钮并且控制台记录状态和 fakeAuth.isAuthenticated 时,它们都返回 true。但是,重定向并未触发。

Login.js

class Login extends Component {
constructor(props) {
super(props);
this.state = {
portalId: "",
password: "",
redirectToReferrer: false
}

this.handleSubmit = this.handleSubmit.bind(this);
}


handleSubmit(e) {
fakeAuth.authenticate(() => {
this.setState({
portalId: this.refs.portalId.value,
password: this.refs.password.value,
redirectToReferrer: true
})
})
e.preventDefault();
}


render() {
const redirectToReferrer = this.state.redirectToReferrer;
if (redirectToReferrer === true) {
<Redirect to="/home" />
}

Routes.js

export const fakeAuth = {
isAuthenticated: false,
authenticate(cb) {
this.isAuthenticated = true
setTimeout(cb, 100)
},
signout(cb) {
this.isAuthenticated = false
setTimeout(cb, 100)
}
}

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={() => (
fakeAuth.isAuthenticated === true
? <Component {...this.props}/>
: <Redirect to="/" />
)}/>
)


export default () => (
<BrowserRouter>
<div>
<Navbar />
<Switch>
<Route path="/" exact component={Login} />
<Route path="/register" exact component={Register} />
<Route path="/home" exact component={Home} />
</Switch>
</div>
</BrowserRouter>
);

最佳答案

您必须在渲染方法中返回Redirect(否则它将不会被渲染,因此不会发生重定向):

  render() {
const redirectToReferrer = this.state.redirectToReferrer;
if (redirectToReferrer) {
return <Redirect to="/home" />
}
// ... rest of render method code
}

关于reactjs - React Router v4 在表单提交时重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49738249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com