javascript - 如何在 Reactjs 的 react-router-dom 版本 5 中使用重定向

标签 javascript reactjs react-router

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

代码:

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;

最佳答案

你必须使用 setState设置将呈现 <Redirect> 的属性在你的里面render()方法。

例如

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/>;
}

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


也就是说,我建议您将 API 调用放在服务或其他东西中。那么你可以只使用 history对象以编程方式路由。 integration with redux 是这样的有效。

但我猜你这样做是有原因的。

关于javascript - 如何在 Reactjs 的 react-router-dom 版本 5 中使用重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43230194/

相关文章:

javascript - 事后为 Facebook 评论添加管理元标签

javascript - 朗读者开始讲话两次

javascript - 如何将skylink集成到react项目中?

twitter-bootstrap - 带有 meteor react Bootstrap 和 react 路由器的标题中的图标

javascript - React - 从另一个组件中的路由路径获取参数

javascript - 如何将 useState 中的不同字符串合并为一个对象?

javascript - 从数组中删除 TableCellElement 会阻止innerHTML 工作吗?

javascript - 使用 React 和 Redux 的收藏夹购物车

javascript - 使用 Context API 与 CloneElement 传递直接后代的 Prop

javascript - 在 React 中切换页面