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

Deadly 提交于 2020-12-13 11:05:08

问题


I developed a Singnup page using Reactjs on the front-end and laravel on the backend and I want when I click on the button register, it will be redirected to my login page.

My Signup component is :

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

My routes is :

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

My index is :

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();

My App.js is :

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;

My react-router-dom version is 4.3.1, when I run that I get :

typeerror: cannot read property 'props' of undefined 

How can I fix that ?


回答1:


try to isolate the property before the axios call:

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



回答2:


You should wrap the signup component with withRouter higher order component to gain access to this.props.history.

More info in react-router docs




回答3:


Just tested this- it redirects just fine.

(within Signup component)..

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>
     )
  }
}

Try it with the above placeholder code to prove that the redirect works without fail, then replace with your custom API + POST. Note: you may need to stringify the POST payload.

We don't know what your App.js looks like, but your App.js would also need to include the <Router /> component.



来源:https://stackoverflow.com/questions/54243931/how-to-redirect-to-another-page-using-history-on-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!