【问题标题】:React Auth state and Routes . Failed to execute 'replaceState' on 'History' inside React-RouterReact Auth 状态和 Routes 。无法在 React-Router 内的“历史”上执行“replaceState”
【发布时间】: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 中身份验证的正确架构吗?

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    我能看到的两件事。

    您不应该重定向到正斜杠而不是反斜杠吗?

    又名将&lt;Redirect to="\" /&gt; 更改为&lt;Redirect to="/" /&gt;

    第二件事是你可能需要升级你的 react-router 版本。问题是您的重定向正试图返回首页,但在重定向到 / 路由时是 there is a bug

    版本 4.6.1 应该会为您正确重定向。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-16
      • 2018-09-12
      • 2018-02-05
      • 1970-01-01
      • 2016-02-04
      • 2021-10-24
      • 2018-08-03
      • 1970-01-01
      相关资源
      最近更新 更多