如何使用 React js 上的历史重定向到另一个页面?

How to redirect to another page using history on React js?

我在前端使用 Reactjs 开发了一个 Singnup 页面,在后端使用 laravel 我希望当我点击注册按钮时,它会被重定向到我的登录页面。

我的注册组件是:

handleSubmit =  event => {
    event.preventDefault();
    const users = {
      name:this.state.name,
      email:this.state.email,
      cin:this.state.cin,
      phoneNumber:this.state.phoneNumber,
      birthDate:this.birthDate,
      password:this.state.password
    }

    console.log(users)

      axios({
        method: 'post',
        url: 'http://172.16.234.24:8000/api/register',
        data: users,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        }
        })
        .then(function (response) {
          console.log(response);
          this.props.history.push('/login');
        })
        .catch(function (response) {
            console.log(response);
        });
  }

我的路线是:

import React from "react";
import { Route, Switch, } from "react-router-dom";
import Home from "./Home";
import NotFound from "./NotFound";
import Login from "./Login";
import Signup from "./Signup";

export default () =>
  <Switch>
    <Route path="/" exact component={Home} />
    <Route path="/login" exact component={Login} />
    <Route path="/signup" exact component={Signup}  />
    <Route component={NotFound} />

  </Switch>;

我的指数是:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from "react-router-dom";
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
<Router>
    <App />
</Router>
    , document.getElementById('root'));
serviceWorker.unregister();

我的 App.js 是:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Nav, Navbar, NavItem } from "react-bootstrap";
import { LinkContainer } from "react-router-bootstrap";
import Routes from "./Routes";
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App container">
        <Navbar fluid collapseOnSelect>
          <Navbar.Header>
            <Navbar.Brand>
              <Link to="/">Home</Link>
            </Navbar.Brand>
            <Navbar.Toggle />
          </Navbar.Header>
          <Navbar.Collapse>
            <Nav pullRight>
              <LinkContainer to="/signup">
                <NavItem>Signup</NavItem>
              </LinkContainer>
              <LinkContainer to="/login">
                <NavItem>Login</NavItem>
              </LinkContainer>
            </Nav>
          </Navbar.Collapse>
        </Navbar>
        <Routes />
      </div>
    );
  }}
export default App;

我的 react-router-dom 版本是 4.3.1,当我 运行 我得到 :

typeerror: cannot read property 'props' of undefined 

我该如何解决?

您应该使用 withRouter 高阶组件包装注册组件以获得对 this.props.history.

的访问权限

More info in react-router docs

刚刚测试过这个 - 它重定向得很好。

(在注册组件内)..

import React, { Component } from "react";
const axios = require('axios');

export default class Signup extends Component {

  constructor(props) {
    super(props); 

    this.state = {}
  }

  handleSubmit = event => {
      event.preventDefault();

        axios({
          method: 'get',
          headers: {
            "Content-type": "application/json"
          },
          url: 'https://jsonplaceholder.typicode.com/todos/1'
          }).then(response => {
            console.log(response); 
            this.props.history.push('/login');
          })
          .catch(response => {
              console.log(response);
          });
    }
  render() {
    return(
       <form onSubmit={this.handleSubmit}>
        <button
          type="submit">
          yo
        </button>
       </form>
     )
  }
}

尝试使用上面的占位符代码来证明重定向正常工作,然后替换为您的自定义 API + POST。注意:您可能需要 stringify POST 负载。

我们不知道您的 App.js 是什么样子,但您的 App.js 还需要包含 <Router /> 组件。

尝试在 axios 调用之前隔离 属性:

  let { history } = this.props

  axios({
    method: 'post',
    url: 'http://172.16.234.24:8000/api/register',
    data: users,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    }
    })
    .then(function (response) {
      console.log(response);
      history.push('/login');
    })
    .catch(function (response) {
        console.log(response);
    });