react 用fetch 登录,成功后怎么跳转组件

1.登录成功后,后台返回的数据到fetch的data里,然后怎么用路由跳转到其他组件呢
2.如果不用路由,可以用window.location.href来跳转到组件吗
handleSubmit = (e) => {

    e.preventDefault();
    // let history = this.context.router.history;
    this.props.form.validateFields((err, values) => {
        if (!err) {
            fetch('/api/login',{
                method:'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type':'application/json;charset=UTF-8'
                },
                body:JSON.stringify({'email':values.email,'password':values.password}),
            }).then(function (res) {
                return res.json();
            }).then(function(data){
                console.log(data)
                // window.location.href='/usercenter';
             
                }
            ).catch(function (err) {
                console.log(err);
            })
        }
    });
}
阅读 6k
2 个回答

如果不使用路由,你可以把要跳转的组件引入进来,然后把当前的组件替换掉
fetch成功之后那数据放到state里面,然后在render下面if判断一下根据数据来显示不同的组件

    import { withRouter } from 'react-router-dom';  // 相对react-router之前版本,react-router4通过withRouter获取history,否则拿不到history
    this.props.history.push('/usercenter');
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题