React Props 未定义

新手上路,请多包涵

我无法理解为什么我的 props.updateBuilding 不起作用。

当道具在渲染方法中时,以下工作

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);
}

但是当我把 this.props.updateBuilding 放到 renderBuildings 方法中,如下所示……

   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>
    );
  }

我得到错误:

 Cannot read property 'props' of undefined

似乎道具 updateBuildings 在 renderBuildings 方法中时无法读取,我不确定是什么原因造成的。

原文由 lost9123193 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 933
2 个回答

你错过了这个错误。 props 不是未定义的,调用的是 props 是未定义的,即 this 关键字。您可以通过传入第二个参数来手动设置 map 函数的上下文

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

或内联绑定

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

原文由 PhilVarg 发布,翻译遵循 CC BY-SA 3.0 许可协议

就我而言,我忘记添加 props 作为构造函数的参数。

 constructor(props) {
  super(props);
}

原文由 spencer.sm 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进