I'm having trouble understanding why my props.updateBuilding is not working.
The following works when the prop is within the render method
class Buildings extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.fetchBuildings();
}
renderBuildings(building) {
return (
<div>
<p> {building.name}</p>
</div>
);
}
render() {
return (
<div>
{this.props.buildings.map(this.renderBuildings)}
<button type="button" className="btn btn-success" onClick={this.props.updateBuilding.bind(this, 1)}>Edit</button>
</div>
);
}
}
function mapStateToProps(state) {
return { buildings: state.buildings.all };
}
function mapDispatchToProps(dispatch){
return bindActionCreators({ fetchBuildings, updateBuilding}, dispatch);
}
But when I put this.props.updateBuilding
to the renderBuildings method like below...
renderBuildings(building) {
return (
<div>
<p> {building.name}</p>
<button type="button" className="btn btn-success" onClick={this.props.updateBuilding.bind(this, building.id)}>Edit</button>
</div>
);
}
I get the error:
Cannot read property 'props' of undefined
It seems that the prop updateBuildings
cannot be read when it is inside the renderBuildings method and I'm not sure what is causing this.
you're miss-reading this error. props
is not undefined, what is calling props
is undefined, which is the this
keyword. you can manually set the context of the map function by passing in a second parameter
this.props.buildings.map(this.renderBuildings, this)
or bind it inline
this.props.buildings.map(this.renderBuildings.bind(this))