React Router v4重定向表单提交

Vin*_*yen 11 reactjs react-router-v4

全新的反应,尝试在"登录"页面上单击提交后重定向到"主页".试图按照路由器反应教程.

当我单击表单和控制台上的提交按钮记录状态和fakeAuth.isAuthenticated时,它们都返回true.但是,重定向未触发.

Login.js

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            portalId: "",
            password: "",
            redirectToReferrer: false
        }

        this.handleSubmit = this.handleSubmit.bind(this);
    }


    handleSubmit(e) {
        fakeAuth.authenticate(() => {
            this.setState({
                portalId: this.refs.portalId.value,
                password: this.refs.password.value,
                redirectToReferrer: true
            })
        })
        e.preventDefault();
    }


    render() {
        const redirectToReferrer = this.state.redirectToReferrer;
        if (redirectToReferrer === true) {
            <Redirect to="/home" />
        }
Run Code Online (Sandbox Code Playgroud)

Routes.js

export const fakeAuth = {
    isAuthenticated: false,
    authenticate(cb) {
        this.isAuthenticated = true
        setTimeout(cb, 100)
    },
    signout(cb) {
        this.isAuthenticated = false
        setTimeout(cb, 100)
    }
}

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={() => (
        fakeAuth.isAuthenticated === true
        ? <Component {...this.props}/>
        : <Redirect to="/" />
    )}/> 
)


export default () => (
    <BrowserRouter>
        <div>
            <Navbar />
            <Switch>
                <Route path="/" exact component={Login} />
                <Route path="/register" exact component={Register} />
                <Route path="/home" exact component={Home} />
            </Switch>
        </div>
    </BrowserRouter>
);
Run Code Online (Sandbox Code Playgroud)

Bar*_*icz 13

你必须返回Redirectrender方法(否则它将不会被渲染,因此不会发生重定向):

  render() {
        const redirectToReferrer = this.state.redirectToReferrer;
        if (redirectToReferrer === true) {
            return <Redirect to="/home" />
        }
        // ... rest of render method code
   }
Run Code Online (Sandbox Code Playgroud)


Vin*_*yen 11

我现在能够通过交换来重定向到“主页”<Redirect to="/home" />this.props.history.push("/home");使用withRouter。不知道为什么第一种方法不起作用。

  • 有一篇关于使用“history.push”和“redirect”之间区别的有用帖子:https://tylermcginnis.com/react-router-programmatically-navigate/ (6认同)