【问题标题】:React 0.14.0-RC1 / React-Router 1.0.0-RC1 - Cannot read property 'props' of nullReact 0.14.0-RC1 / React-Router 1.0.0-RC1 - 无法读取 null 的属性“道具”
【发布时间】:2016-01-01 05:05:38
【问题描述】:

我正在 Alex Bank 的 "Building a Polling App with Socket IO 工作 和 React.js" (Lynda.com),但我正在尝试将其升级到 反应路由器 1.0.0-RC1.


我的github repository can be found here ....

问题:

当演讲者登录并创建演示文稿时,会显示成功的问题列表。但是,当演讲者单击要向与会者发出的相应问题时,我收到错误:"Cannot read property 'props' of null",它标识了 Question.js 组件中的错误:

ask(question) {
  console.log('this question: ' + JSON.stringify(question));
  this.props.emit('ask', question); <--- Console points to this
}

但我不认为这本身就是问题所在。我相信实际的问题是这个发射没有到达应用程序中的 socket.on。

APP.js:

componentWillMount() {
  this.socket = io('http://localhost:3000');
  this.socket.on('ask', this.ask.bind(this));
  ....
}

ask(question) {
  sessionStorage.answer = '';
  this.setState({ currentQuestion: question });
}

相信它与react-router相关,但父路由确实有组件{APP},并且Speaker是子路由并且Speaker组件确实导入了Question组件,所以我假设Question组件连接到APP的。

在亚历克斯的项目中它正在工作,但他使用:

  "react": "^0.13.3",
  "react-router": "^0.13.3", 

有人可以提供一些关于这方面的见解吗?

非常感谢!

【问题讨论】:

    标签: socket.io reactjs react-router


    【解决方案1】:

    如果您的错误提示“无法读取 null 的属性 'props'”,这正是正在发生的事情:您正试图在 null 的值上调用 .props

    然而,真正的问题在于这段代码:

    ask(question) {
      console.log('this question: ' + JSON.stringify(question));
      this.props.emit('ask', question);
    }
    
    addQuestion(question, index) {
      return (
        <div key={ index } className="col-xs-12 col-sm-6 col-md-3">
          <span onClick={ this.ask.bind(null, question) }>{ question.q }</span>
        </div>
      );
    }
    

    具体来说,this code(未包含在问题中):

    onClick={ this.ask.bind(null, question) }>
    

    您正在为绑定到nullthis.ask 版本分配一个点击处理程序;这适用于React.createClass-type 组件,因为 React 强制并自动将所有组件方法绑定到组件实例,无论您将什么作为第一个参数传递给 .bind() (所以null 是常用的;我认为否则,React 实际上会对你大喊大叫)。然而,对于 ES6 类,情况并非如此。您实际上是在将this 内的ask() 设置为null

    正确的版本应该是

    onClick={ this.ask.bind(this, question) }>
    

    或者,通常作为匿名函数

    onClick={ () => this.ask(question) }>
    

    【讨论】:

    • 按照您的建议进行更改(我什至将其推送到github),我收到一个新错误,“this.props.emit is not a function”,显然与APP的映射有关(@987654322 @)
    • @SarasotaSun 知道扔在哪里会很有帮助。我浏览了代码,看到了与我在此处 in Ask.js on line 50 描述的完全相同的问题,但我认为在这种情况下您也会看到 this.setState 的问题。
    • 你点击了一个缓存的blob,如果你直接去repo,你会看到我做了改变,错误指向同一行。
    • @SarasotaSun 你可以做的另一件事是将你的非可选道具的propTypes 设置为.isRequired,这样如果组件没有收到道具,React 会提前警告你它应该有。
    • @SarasotaSun 不,我创建了那个缓存的 URL。到目前为止,这在 GitHub 上的 master 分支上仍然是错误的。
    【解决方案2】:

    错误消息表明this 为空。原因是 react 不会自动将 this 绑定到 react 元素。也就是说,this 在调用ask(question) 方法时不会引用元素本身。你只需要将它绑定在constructor:this.ask = this.ask.bind(this)。你最好阅读official react blog上的ES6课堂笔记。

    阅读react-router upgrade guide也是一个好主意:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-20
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多