使用包
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
authState: null,
};
}
mutateAuthState = () => {
this.setState({
authState: true,
});
}
render() {
return (<Routes authState={this.state.authState} mutateAuthState={this.mutateAuthState} />)
}
}
Routes.js
class Routes extends React.Component {
render() {
return (
<React.Fragment>
<BrowserRouter >
<Switch>
<Route path="/login" exact render={ () => <Login authState={this.props.authState}
mutateAuthState={this.props.mutateAuthState}/>
} />
<Route path="/" exact render={ () => <div><a href="/login" >login</a></div> } />
</Switch>
</BrowserRouter>
</React.Fragment>
);
}
}
Login.js
class Login extends Component {
handleSubmit = async (event) => {
this.props.mutateAuthState(true)
}
render() {
switch(this.props.authState) {
case true : return (<Redirect to="\" />)
default : return(
<button onClick={this.handleSubmit} >Login </button>
)
}
}
}
希望获得最终结果-单击Login.js中的“登录”按钮会将App.js中的状态变量authState设置为true。
由于状态已更改,应用将重新渲染Routes.js。
在Routes内部,由于url仍然是/ login,因此呈现了Login组件。
在Login内部,由于this.props.authState现在设置为true,因此发生了到“ /”的重定向。
但是我在Web Console中收到DOMException
错误:DOMException:无法在“历史记录”上执行“ replaceState”:不能在源为“ http:// localhost:3000 ”且URL为“ http:// localhost ”的文档中创建URL为“ http:”的历史状态对象:3000 / login '。
这是React中身份验证的适当架构吗?
我可以看到两件事。
您不应该重定向到正斜杠而不是反斜杠吗?
又名更改<Redirect to="\" />
为<Redirect to="/" />
第二件事是您可能需要升级您的react-router版本。问题是您的重定向正试图回到家中,但是重定向到路由时出现错误/
。
版本4.6.1
应该为您正确重定向。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句