如何在 Reactjs 的 react-router-dom 版本 5 中使用 Redirect

新手上路,请多包涵

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

代码:

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;

原文由 maoooricio 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

您必须使用 setState 来设置将在您的 render() 方法中呈现 <Redirect> 的属性。

例如

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 对象以编程方式进行路由。这就是 与 redux 集成的 方式。

但我想你有理由这样做。

原文由 Sebastian Sebald 发布,翻译遵循 CC BY-SA 4.0 许可协议

这里有一个小例子作为对标题的回应,因为我认为所有提到的例子和官方例子都很复杂。

您应该知道如何转译 es2015 以及如何让您的服务器能够处理重定向。这是 express 的一个片段。可以在 此处 找到与此相关的更多信息。

确保将其放在所有其他路线下方。

 const app = express();
app.use(express.static('distApp'));

/**
 * Enable routing with React.
 */
app.get('*', (req, res) => {
  res.sendFile(path.resolve('distApp', 'index.html'));
});

这是 .jsx 文件。请注意最长的路径是如何排在第一位并变得更通用。对于大多数通用路由,请使用 exact 属性。

 // Relative imports
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';

// Absolute imports
import YourReactComp from './YourReactComp.jsx';

const root = document.getElementById('root');

const MainPage= () => (
  <div>Main Page</div>
);

const EditPage= () => (
  <div>Edit Page</div>
);

const NoMatch = () => (
  <p>No Match</p>
);

const RoutedApp = () => (
  <BrowserRouter >
    <Switch>
      <Route path="/items/:id" component={EditPage} />
      <Route exact path="/items" component={MainPage} />
      <Route path="/yourReactComp" component={YourReactComp} />
      <Route exact path="/" render={() => (<Redirect to="/items" />)} />
      <Route path="*" component={NoMatch} />
    </Switch>
  </BrowserRouter>
);

ReactDOM.render(<RoutedApp />, root);

原文由 Matthis Kohli 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题