javascript - 传递给 React 函数后参数未定义?

标签 javascript reactjs parameter-passing react-props

在 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_idstatus 在传递时是 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/

相关文章:

javascript - 使用 jasmine 模拟函数调用

javascript - 获取 php 样式表输出并存储为变量

javascript - 在 React Native SectionList 中使用来自 Firebase 的数据。数据结构问题

javascript - 按住移动按钮时如何防止附近的文本选择?

c++ - 使用函数指针将字符串数组作为参数传递

javascript - Jquery - 将光标放在 iframe 中时无法设置 keydown 事件(文本编辑器)

javascript - 任何想法为什么这个 react 组件按钮 onClick 不会被触发

variables - LESS:将带有变量的规则集(或 mixin)传递给另一个 mixin 并能够使用这些变量

arrays - 在不定义变量的情况下将数组作为函数参数传递

javascript - 如何在 Meteor JS 中使用路由器动态更改正文模板?