【发布时间】:2018-08-28 00:24:21
【问题描述】:
在 Home 组件中我们要调用一个函数:
refreshMatchStatus = (match_id, status) => {
console.log(match_id)
var matches = this.state.matches
matches.map(function(match){
if (match.id == match_id){
match.challenged = status
}
})
this.setState({matches: matches})
}
从 Home 渲染这个函数被传递到下一个组件:
<List refreshMatchStatus={this.refreshMatchStatus.bind(this)} showAlert={this.props.showAlert} user={this.state.user} token={this.state.token} matches={this.state.matches}/>
然后通过一些组件向下传递函数,如下所示:
refreshMatchStatus={this.props.refreshMatchStatus}
当它到达 ChallengePopup 组件时,它是这样执行的:
this.props.refreshMatchStatus(match_id, status)
由于某种原因,参数match_id 和status 在传递时是undefined。
如果我们在 ChallengePopup 组件中执行console.log,在调用函数前一行,match_id 将返回正确的 id 号。但是当我们在 refreshMatchStatus 函数的第一行执行console.log 时,match_id 返回undefined。
我们怀疑 this 与 bind(this) 有关,但我们找不到任何方法以正确的方式传递参数。
【问题讨论】:
-
您应该显示包含
<List refreshMatchStatus={this.refreshMatchStatus.bind(this)} ...>的组件代码 -
能否贴出所有相关组件/功能的完整代码?
-
我过去确实遇到过同样的问题,我解决它的方法是在子组件中为道具设置默认值希望意外地解决了我的问题
-
事实上我相信你根本不需要绑定,因为
refreshMatchStatus是一个箭头函数,它总是会在定义它的上下文中调用。 -
您一定在代码中的任何地方错过了一个您没有在此处添加的问题。这是不可重现的。 See the minimal codesandbox example I created.
标签: javascript reactjs parameter-passing react-props