当前位置 : 主页 > 网页制作 > React >

reactjs – React Router v4重定向表单提交

来源:互联网 收集:自由互联 发布时间:2021-06-15
全新的反应,尝试在“登录”页面上单击提交后重定向到“主页”.试图按照路由器反应教程. 当我单击表单和控制台上的提交按钮记录状态和fakeAuth.isAuthenticated时,它们都返回true.但是,重
全新的反应,尝试在“登录”页面上单击提交后重定向到“主页”.试图按照路由器反应教程.

当我单击表单和控制台上的提交按钮记录状态和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" />
        }

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>
);
您必须在render方法中返回Redirect(否则它将不会被渲染,因此不会发生重定向):

render() {
        const redirectToReferrer = this.state.redirectToReferrer;
        if (redirectToReferrer === true) {
            return <Redirect to="/home" />
        }
        // ... rest of render method code
   }
网友评论