【问题标题】:I can't implement Redirect in React我无法在 React 中实现重定向
【发布时间】:2019-09-07 08:39:33
【问题描述】:

当某些条件返回null或false但没有触发Redirect的动作时,我想重定向到主页。

import { Link, Redirect } from "react-router-dom";

if(localStorage.getItem("example") === null || localStorage.getItem("example") === false){
    return <Redirect to="/" />
}

我将这段代码放在一个简单的函数中,该函数在OnClickcomponentDidMount() 中触发,但它不起作用。

【问题讨论】:

    标签: reactjs redirect react-router


    【解决方案1】:

    您可以使用重定向到主页,基于可以通过在 onClickHandler 或 handleSubmit 中使用 setState 更改的重定向标志。

    import { Redirect } from "react-router-dom";
    
    class MyComponent extends React.Component {
      state = {
        redirect: false
      }
    
      handleSubmit () {
        if(localStorage.getItem("example") === null || localStorage.getItem("example") === false){
          return this.setState({ redirect: true });
        }
      }
    
      render () {
        const { redirect } = this.state;
    
        if (redirect) {
          return <Redirect to='/'/>;
        }
        return <YourForm/>;
    }
    

    【讨论】:

      【解决方案2】:

      您需要使用 Redirect inside 渲染。它是一个 React 组件,它呈现然后将用户发送到所需的路径:

      import React, { Component } from "react";
      import { Route, Switch, Redirect } from "react-router-dom";
      
      class RootPage extends React.Component {
        state = {
          isLoggedOut: false
        };
      
        onClick = () => {
          this.setState({
            isLoggedOut: true
          });
        };
      
        render() {
          return (
            <div>
              {this.state.isLoggedOut && <Redirect to="/logout" />}
              <button onClick={this.onClick}>Logout</button>
            </div>
          );
        }
      }
      
      const Log = () => <h1>Logout</h1>;
      
      class App extends Component {
        render() {
          return (
            <div>
              <nav className="navbar navbar" />
              <Switch>
                <Route exact path="/" component={RootPage} />
                <Route exact path="/logout" component={Log} />
              </Switch>
            </div>
          );
        }
      }
      export default App;
      

      当您单击注销按钮时,它会将您重定向到 rootPath。

      这里是演示:https://codesandbox.io/s/q9v2nrjnx4

      【讨论】:

        【解决方案3】:

        查看官方文档中的this example

        如果您使用类组件,&lt;Redirect /&gt; 应该在您的 render 方法中。或者如果你使用一个函数组件,它应该在它返回的内容中。

        示例如下:

        import { Component } from 'react';
        
        const PrivateComponent = (props) => {
          return(
            localStorage.getItem("example")
              ? <RandomComponent />
              : <Redirect to="/signin" />
          )
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-20
          • 2019-08-11
          • 1970-01-01
          • 2021-07-24
          • 2016-12-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多