在 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 render 传递到下一个组件:
<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
。
我们怀疑这与 bind(this) 有关,但我们找不到任何方法以正确的方式传递参数。
最佳答案
例如将您的绑定(bind)调用移至构造函数
constructor(props) {
super(props);
this.refreshMatchStatus = this.refreshMatchStatus.bind(this);
}
然后您可以删除渲染方法中的 .bind
调用,否则由于它是父组件,每次触发新渲染时都会重置方法绑定(bind),我相信这会导致丢失 children 的争论。
关于javascript - 传递给 React 函数后参数未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49363030/