React改用箭头函数替代bind绑定 触发value属性读取未定义报错
报错核心原因
报错和箭头函数的this绑定逻辑没有关联,本质是父子组件间的props传值、接收完全不匹配,导致读取了不存在的属性。
- 父组件
Counters给子组件Counter实际传入的props为:key、id、value、onDelete、onIncrement - 子组件
Counter代码中尝试读取的props为:counter、handleIncrement,这两个值从未被传入,因此读取属性时触发Cannot read property 'value' of undefined。
具体不匹配的代码位置
- 子组件内部读取不存在的
counterprop的位置:formatCount方法中:const { value } = this.props.countergetBadgeClasses方法中:this.props.counter.value === 0
因为this.props.counter是undefined,读取其value属性直接触发报错。
- 按钮事件中读取不存在的方法prop:
增量按钮绑定的事件是this.props.handleIncrement,但父组件实际传入的事件方法名是onIncrement。
修正方案
两种等价的修正路径二选一即可:
方案1:匹配现有父组件的传参逻辑,修改子组件代码
- 调整子组件读取value的逻辑,直接读父组件传入的
valueprop,不再读不存在的counter对象:formatCount(){ const { value } = this.props; return value === 0 ? "Zero" : value; } getBadgeClasses(){ let classes="badge p-3 badge-"; classes += this.props.value === 0 ? "warning":"primary"; return classes } - 修正增量按钮的事件绑定,匹配父组件传入的方法名,按需传参:
<button onClick={() => this.props.onIncrement({ id: this.props.id, value: this.props.value })} className="btn btn-secondary btn-sm m-2 p-3" > Increment </button>
方案2:匹配现有子组件的读取逻辑,修改父组件的传参
- 父组件遍历counters数组时,把整个counter对象作为单独的prop传入:
{this.state.counters.map(counter => <Counter key={counter.id} onDelete={this.handleDelete} onIncrement={this.handleIncrement} counter={counter} id={counter.id} /> )} - 修正子组件增量按钮的事件绑定,把不存在的
handleIncrement改为父组件传入的onIncrement:<button onClick={() => this.props.onIncrement(this.props.counter)} className="btn btn-secondary btn-sm m-2 p-3" > Increment </button>
注:你在父组件中使用类属性箭头函数(如
handleIncrement=counter => {})的写法完全可以正确绑定this,不需要额外手动bind,本次报错和this绑定逻辑无关。
内容的提问来源于stack exchange,提问作者dil. 1122
相关产品推荐
相关产品推荐

