如何在 Reactjs 的新 react-router-dom 中使用 Redirect [英] How to use Redirect in the new react-router-dom of Reactjs

查看:26
本文介绍了如何在 Reactjs 的新 react-router-dom 中使用 Redirect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是最新版本的 react-router 模块,名为 react-router-dom,它已成为使用 React 开发 Web 应用程序时的默认设置.我想知道如何在 POST 请求后进行重定向.我一直在制作这段代码,但是在请求之后,什么也没有发生.我在网上查看过,但所有数据都是关于之前版本的 react 路由器,与上次更新无关.

代码:

import React, { PropTypes } from 'react';从 'react-dom' 导入 ReactDOM;从'react-router-dom'导入{ BrowserRouter};从反应路由器"导入{重定向}从'../../register/components/SignUpForm'导入SignUpForm;从'./PagesStyles.css'导入样式;从 'axios' 导入 axios;从'../../shared/components/Footer'导入页脚;class SignUpPage 扩展 React.Component {构造函数(道具){超级(道具);this.state = {错误:{},客户: {用户客户端:'',客户名称: '',客户企业名称:'',密码: '',确认密码: ''}};this.processForm = this.processForm.bind(this);this.changeClient = this.changeClient.bind(this);}更改客户端(事件){const 字段 = event.target.name;const 客户端 = this.state.client;客户端[字段] = event.target.value;this.setState({客户});}异步 processForm(事件){event.preventDefault();const userclient = this.state.client.userclient;const clientname = this.state.client.clientname;const clientbusinessname = this.state.client.clientbusinessname;const 密码 = this.state.client.password;const confirmPassword = this.state.client.confirmPassword;const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };axios.post('/signup', formData, { headers: {'Accept': 'application/json'} }).then((响应) => {this.setState({错误:{}});<重定向到="/"/>//在这里,什么都没有发生}).catch((错误) => {const 错误 = error.response.data.errors ?error.response.data.errors : {};errors.summary = error.response.data.message;this.setState({错误});});}使成为() {返回 (<div className={styles.section}><div className={styles.container}><img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground}/><注册表格onSubmit={this.processForm}onChange={this.changeClient}错误={this.state.errors}客户端={this.state.client}/><页脚/>

);}}导出默认注册页面;

解决方案

您必须使用 setState 来设置一个属性,该属性将在您的内部呈现 render() 方法.

例如

class MyComponent 扩展 React.Component {状态 = {重定向:假}句柄提交(){axios.post(/**/).then(() => this.setState({redirect: true }));}使成为 () {const { 重定向 } = this.state;如果(重定向){return <Redirect to='/somewhere'/>;}返回 <RenderYourForm/>;}

你也可以在官方文档中看到一个例子:https://reacttraining.com/react-router/web/example/auth-workflow

<小时>

也就是说,我建议您将 API 调用放在服务或其他东西中.然后您可以使用 history 对象以编程方式进行路由.这就是 与 redux 集成的方式 有效.

但我想你有理由这样做.

I am using the last version react-router module, named react-router-dom, that has become the default when developing web applications with React. I want to know how to make a redirection after a POST request. I have been making this code, but after the request, nothing happens. I review on the web, but all the data is about previous versions of the react router, and no with the last update.

Code:

import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Redirect } from 'react-router'

import SignUpForm from '../../register/components/SignUpForm';
import styles from './PagesStyles.css';
import axios from 'axios';
import Footer from '../../shared/components/Footer';

class SignUpPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      errors: {},
      client: {
        userclient: '',
        clientname: '',
        clientbusinessname: '',
        password: '',
        confirmPassword: ''
      }
    };

    this.processForm = this.processForm.bind(this);
    this.changeClient = this.changeClient.bind(this);
  }

  changeClient(event) {
    const field = event.target.name;
    const client = this.state.client;
    client[field] = event.target.value;

    this.setState({
      client
    });
  }

  async processForm(event) {
    event.preventDefault();

    const userclient = this.state.client.userclient;
    const clientname = this.state.client.clientname;
    const clientbusinessname = this.state.client.clientbusinessname;
    const password = this.state.client.password;
    const confirmPassword = this.state.client.confirmPassword;
    const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };

    axios.post('/signup', formData, { headers: {'Accept': 'application/json'} })
      .then((response) => {
        this.setState({
          errors: {}
        });

        <Redirect to="/"/> // Here, nothings happens
      }).catch((error) => {
        const errors = error.response.data.errors ? error.response.data.errors : {};
        errors.summary = error.response.data.message;

        this.setState({
          errors
        });
      });
  }

  render() {
    return (
      <div className={styles.section}>
        <div className={styles.container}>
          <img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} />
          <SignUpForm 
            onSubmit={this.processForm}
            onChange={this.changeClient}
            errors={this.state.errors}
            client={this.state.client}
          />
          <Footer />
        </div>
      </div>
    );
  }
}

export default SignUpPage;

解决方案

You have to use setState to set a property that will render the <Redirect> inside your render() method.

E.g.

class MyComponent extends React.Component {
  state = {
    redirect: false
  }

  handleSubmit () {
    axios.post(/**/)
      .then(() => this.setState({ redirect: true }));
  }

  render () {
    const { redirect } = this.state;

     if (redirect) {
       return <Redirect to='/somewhere'/>;
     }

     return <RenderYourForm/>;
}

You can also see an example in the official documentation: https://reacttraining.com/react-router/web/example/auth-workflow


That said, I would suggest you to put the API call inside a service or something. Then you could just use the history object to route programatically. This is how the integration with redux works.

But I guess you have your reasons to do it this way.

这篇关于如何在 Reactjs 的新 react-router-dom 中使用 Redirect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆