Sho*_*cob 6 reactjs react-router-dom
使用包
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
Run Code Online (Sandbox Code Playgroud)
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} />)
}
}
Run Code Online (Sandbox Code Playgroud)
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
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>
)
}
}
}
Run Code Online (Sandbox Code Playgroud)
想要的最终结果 - 在Login.js中单击Login按钮会将App.js中的状态变量authState设置为true.
应用程序将重新运行Routes.js,因为状态已发生变化.
在路由内部,由于url仍为/ login,因此将呈现Login组件.
在Login中,由于this.props.authState现在设置为true,因此会重定向到"/".
但是我在Web控制台中收到了一个DOMException
错误:DOMException:无法在"历史记录"上执行"replaceState":无法在源为" http:// localhost:3000 "且URL为" http:// localhost " 的文档中创建URL为"http:"的历史状态对象:3000 /登录 '.
这是React中身份验证的正确架构吗?
| 归档时间: |
|
| 查看次数: |
496 次 |
| 最近记录: |