The requisite reaction is not defined

I am having trouble understanding why my props.updateBuilding is not working.

The following works when prop is inside 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.updateBuildingin the renderBuildings method as shown 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 an error message:

Cannot read property 'props' of undefined

It seems that prop updateBuildingscannot be read when it is inside the renderBuildings method, and I'm not sure what causes this.

+4
source share
3 answers

. props undefined, , props, undefined, this. ,

this.props.buildings.map(this.renderBuildings, this)

this.props.buildings.map(this.renderBuildings.bind(this))

+8

props .

constructor(props) {
  super(props);
}
+7

try:

this.props.buildings.map(this.renderBuildings.bind(this))
+2
source

Source: https://habr.com/ru/post/1660876/


All Articles