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.
The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.
The "cannot set property 'props' of undefined" error occurs when we add an extra set of parenthesis when declaring a class component in React. js. To solve the error, remove the parenthesis after Component in your class declaration, e.g. class App extends Component {} . Here is an example of how the error occurs.
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App. jsx'; ReactDOM. render(<App headerProp = "Header from props..." contentProp = "Content from props..."/>, document.
The React. js error "X is not defined react/jsx-no-undef" occurs when we forget to import a function, class or a variable in our code before using it. To solve the error, make sure to import the value before using it in your code, e.g. import {myFunc} from 'my-package' . Copied!
In my case, I forgot to add props
as an argument to the constructor.
constructor(props) {
super(props);
}
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With