【发布时间】:2019-03-29 13:41:46
【问题描述】:
使用包
"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>
);
}
}
登录.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 控制台中遇到 DOMException
错误:DOMException:无法在“历史”上执行“replaceState”:A 无法在文档中创建 URL 为“http:”的历史状态对象 带有原点“http://localhost:3000”和 URL 'http://localhost:3000/login'。
这是 React 中身份验证的正确架构吗?
【问题讨论】: