【问题标题】:Arguments undefined after passing to React function?传递给 React 函数后参数未定义?
【发布时间】: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_idstatus 在传递时是undefined

如果我们在 ChallengePopup 组件中执行console.log,在调用函数前一行,match_id 将返回正确的 id 号。但是当我们在 refreshMatchStatus 函数的第一行执行console.log 时,match_id 返回undefined

我们怀疑 this 与 bind(this) 有关,但我们找不到任何方法以正确的方式传递参数。

【问题讨论】:

  • 您应该显示包含&lt;List refreshMatchStatus={this.refreshMatchStatus.bind(this)} ...&gt;的组件代码
  • 能否贴出所有相关组件/功能的完整代码?
  • 我过去确实遇到过同样的问题,我解决它的方法是在子组件中为道具设置默认值希望意外地解决了我的问题
  • 事实上我相信你根本不需要绑定,因为refreshMatchStatus 是一个箭头函数,它总是会在定义它的上下文中调用。
  • 您一定在代码中的任何地方错过了一个您没有在此处添加的问题。这是不可重现的。 See the minimal codesandbox example I created.

标签: javascript reactjs parameter-passing react-props


【解决方案1】:

将绑定调用移至构造函数,例如

constructor(props) {
    super(props);
    this.refreshMatchStatus = this.refreshMatchStatus.bind(this);
}

然后您可以在您的渲染方法中删除.bind 调用,否则由于它是父组件,每次触发新渲染时,方法绑定都会重置,我认为这会导致子级参数丢失。

【讨论】:

  • 将绑定移动到构造函数是个好主意,但我看不出这会如何导致参数丢失
  • 好吧,他的问题底部说“我们怀疑它可能与绑定有关”,所以我提供了一种替代方法,让他们自己确定:)
  • 是的,你的回答很有价值,只是好奇它为什么/如何影响!
猜你喜欢
  • 1970-01-01
  • 2011-10-21
  • 2016-06-14
  • 2015-03-08
  • 1970-01-01
  • 2021-12-05
  • 2021-11-24
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多