this.props.history showing undefine in console in React JS

百般思念 提交于 2021-02-11 13:19:17

问题


In my react app I want to send state to the next path through the history.location.state and history.location.pathname

In my case, it has to push successfully and also showing in history but when I console.log(this.props.history) in the child page showing undefined.

MyComponent Code

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class MyComponent extends Component {
state = {
          cart: {
                    1:{
                       icon: "URL"
                       id: 1
                       quantity: 1
                       title: "item1"
                      }
                    2:{
                       icon: "URL"
                       id: 2
                       quantity: 1
                       title: "item2"
                      }
             }
        }

submitHandler = (event) => {
        event.preventDefault();
        let data = {};
        for (let key in this.state.cart) {
            data[key] = this.state.cart[key]
        }
        console.log("data=",data);
        this.props.history.push({
            pathname: "/result",
            state: { data: data }
        });

    }

render(){
return(
             <div >
               <button  onClick={this.submitHandler}>CONTINUE</button>
             </div>
         )
     }
}
export default withRouter(MyComponent);

Result Component

import React, { Component } from 'react';

class Result extends Component {
render() {

        console.log("ss=",this.props.history);

        return(<div>Result</div>)
}

export default Result;

In Console

Route

<Route path="/result" component={Result} />

As shown in the above img in history->location->state is push fine. But when I console log to this.props showing undefined.

Also I already use withRouter hoc of react-router-dom in export

Suggest me a solution to this?


回答1:


May be you are called wrong path. its working and the state variable available on this.props.location not a this.props.history;

Codesanbox example



来源:https://stackoverflow.com/questions/65827451/this-props-history-showing-undefine-in-console-in-react-js

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