最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to redirect to another page using history on React js? - Stack Overflow

programmeradmin5浏览0评论

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 ponent 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 ponent={Home} />
    <Route path="/login" exact ponent={Login} />
    <Route path="/signup" exact ponent={Signup}  />
    <Route ponent={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 ?

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 ponent 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 ponent={Home} />
    <Route path="/login" exact ponent={Login} />
    <Route path="/signup" exact ponent={Signup}  />
    <Route ponent={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 ?

Share Improve this question edited Jan 18, 2019 at 8:35 Ichrak Mansour asked Jan 17, 2019 at 20:37 Ichrak MansourIchrak Mansour 1,95212 gold badges37 silver badges64 bronze badges 3
  • 2 Try using an arrow function on then callback. – gugadev Commented Jan 17, 2019 at 20:41
  • 1 @gugadev I try : .then =(response)=> { console.log(response); this.props.history.push('/login'); } but it is still the same issue. – Ichrak Mansour Commented Jan 17, 2019 at 20:54
  • look, this function will run at axios. Maybe you need to preserve the "this" to use internally. – Joao Polo Commented Jan 17, 2019 at 21:54
Add a ment  | 

3 Answers 3

Reset to default 2

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

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

More info in react-router docs

Just tested this- it redirects just fine.

(within Signup ponent)..

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./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 /> ponent.

发布评论

评论列表(0)

  1. 暂无评论