问题
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