ウェブサイト検索

javascript - Reactjsのreact-router-domバージョン5でRedirectを使用する方法


私は最新バージョンの react-router モジュールである react-router-dom を使用しています。これは、React でウェブアプリケーションを開発する際のデフォルトになっています。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;

回答 #1

あなたは、render() メソッド内で <Redirect> をレンダーするプロパティを設定するために、setState を使用する必要があります。

例

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 との統合の方法です。

でも、こうする理由があなたにはあるのでしょうね。

回答 #2

ここに、小さな例を示します。タイトルへの応答としてです。私の意見では、言及されたすべての例や公式のものも複雑です。

あなたは、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); 

回答 #3

React Router v5では、useHistory()フックのおかげで、history.push()を使って簡単にリダイレクトすることができるようになりました。

import { useHistory } from "react-router-dom"

function HomeButton() {
  let history = useHistory()

  function handleClick() {
    history.push("/home")
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  )
}

回答 #4

任意の関数内でそれを呼び出すだけです。

this.props.history.push('/main');

関連記事