I don't understand one thing, why is that giving me an error "TypeError: Cannot read property 'props' of undefined"?
import React from 'react';
import { withRouter } from 'react-router-dom';
import * as ROUTES from '../../../constants/routes';
function Summary({ reservationData }) {
if (reservationData.participants !== "" && reservationData.city !== "" && reservationData.day !== "" && reservationData.hour !== "") {
return (
<div>Summary<br />
Participants: {reservationData.participants} <br />
City: {reservationData.city} <br />
Day: {reservationData.day} <br />
Hour: {reservationData.hour} <br />
{console.log(reservationData)}
</div>
);
} else {
{ this.props.history.push(ROUTES.RESERVATION) }
}
}
It is giving me an error on that last line in else statement
} else {
{ this.props.history.push(ROUTES.RESERVATION) }
}
Summary
is a functional component and doesn't have access to this
. In order to use props.history
in a function component you can destructure the arguments like below.
function Summary({ reservationData, history }) {
if (reservationData.participants !== "" && reservationData.city !== "" && reservationData.day !== "" && reservationData.hour !== "") {
return (
<div>Summary<br />
Participants: {reservationData.participants} <br />
City: {reservationData.city} <br />
Day: {reservationData.day} <br />
Hour: {reservationData.hour} <br />
{console.log(reservationData)}
</div>
);
} else {
history.push(ROUTES.RESERVATION;
}
}
Can see that you are doing in a Class Component way.
If you used to use props in your component you can do
function Summary(props) {
// Then access the history and reservationData in this way
const { reservationData, history } = props
history.push(ROUTES.RESERVATION);
// Or
props.history.push(ROUTES.RESERVATION)
}
If you think the code is a little bit troublesome, You can follow what Shubham Khatri did
function Summary({ reservationData, history}) {
history.push(ROUTES.RESERVATION)
}
this.props is only able to use in class Component.
All of these is valid, writing style is up to you, feel free to try different approach, Happy Learning.
if you want to use this
. you have to create component in class react style.
class Summary extends React.Component {
render() {
//...
this.props.history.push(ROUTES.RESERVATION)
}
}
export default withRouter(Summary)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.