【问题标题】:Cannot Access Properties in Callback Function React无法访问回调函数 React 中的属性
【发布时间】:2017-12-22 02:38:19
【问题描述】:

我正在使用一个名为 Papa Parse 的库将 csv 文件解析为 json。解析器工作正常,但我无法在 Papa 解析的配置对象的“完整”部分中指定的回调函数中调用我的操作创建者。我相信这是一个范围问题,但我一直无法解决。下面感兴趣的主要部分是为什么我不能调用“printFile”函数中的任何一个函数,最重要的是“addRoster”函数。请让我知道您有任何建议或想法。谢谢!

编辑:忽略这是 sn-p 形式。这里的内容不可运行,我只是无法让格式化工作。

class Roster extends Component {

  super(props) {

    this.printFile = this.printFile.bind(this);

    this.testMethod = this.testMethod.bind(this);
  }

  componentWillMount() {
    this.props.addRoster('test')
  }

  printFile(results, file) {
    this.props.addRoster(file);
    this.props.testMethod;
  }

  testMethod(test) {
    console.log("Winner")
  }

  fileDrop(file) {

    var config = {
      delimiter: "", // auto-detect
      newline: "", // auto-detect
      quoteChar: '"',
      header: true,
      dynamicTyping: false,
      preview: 0,
      encoding: "",
      worker: false,
      comments: false,
      step: undefined,
      complete: this.printFile,
      error: undefined,
      download: false,
      skipEmptyLines: false,
      chunk: undefined,
      fastMode: undefined,
      beforeFirstChunk: undefined,
      withCredentials: undefined
    }
    Papa.parse(file, config)
  }


  render() {
    const {
      addRoster
    } = this.props;

    return ( <
      Grid >
      <
      Row >
      <
      MyDropzone onFileDrop = {
        this.fileDrop.bind(this)
      }
      /> < /
      Row > <
      /Grid>
    )
  }

}

export default connect(null, {
  addRoster
})(Roster);

【问题讨论】:

  • 运行代码sn -p,出现错误"message": "Uncaught SyntaxError: Unexpected token &lt;",
  • 抱歉,sn-p 不应该是可运行的。我只是使用它,因为我无法让括号格式工作。 @ppz
  • 您能否在printFile 函数中使用console.log(this) 来了解范围。我假设,这个回调是用预定义的上下文调用的

标签: javascript reactjs scope react-redux


【解决方案1】:

我认为你没有添加构造函数所以函数没有绑定?尝试更改此设置

super(props) 
{
  this.printFile = this.printFile.bind(this);
  this.testMethod = this.testMethod.bind(this);
}

到

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

【讨论】:

  • 哇,我的粗心错误。这固定了。感谢您的帮助!
  • 嗨,如果该答案有帮助,请投票并接受答案。这个小小的奖励将帮助像我这样的人回答更多的问题,谢谢
  • 嘿,对不起。系统很新。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2017-02-27
  • 2011-11-05
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多