React 0.14.0-RC1 / React-Router 1.0.0-RC1 - 无法读取null

时间:2015-10-04 12:21:33

标签: socket.io reactjs react-router

  

我正在处理 Alex Bank的"Building a Polling App with Socket IO and React.js" (Lynda.com),但我正在努力将其升级为   react-router 1.0.0-RC1。

  

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

问题:

当演讲者登录并创建演示文稿时,会出现成功的问题列表。但是,当发言者点击相应的问题以向与会者发出时,我收到错误:“无法读取属性'道具'为null”,它标识了Question.js组件中的错误:< / p>

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组件,所以我假设问题组件连接到APP的。

在Alex的项目中,它正在运作,但他使用:

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

有人可以向我提供一些有关此事的见解吗?

非常感谢!

2 个答案:

答案 0 :(得分:5)

如果您的错误显示“无法读取属性'道具'为null,”这正是发生的事情:您正在尝试使用.props的值调用null

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

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) }>

您将点击处理程序分配给绑定到this.ask的{​​{1}}版本;这适用于null - 类型组件,因为React强制并自动将所有组件方法绑定到组件实例,无论您传递的是React.createClass的第一个参数(以及.bind()是常用的;我认为React实际上会对你大喊大叫)。但是,ES6课程并非如此;您确实将null内的this设置为ask()

正确的版本是

null

或通常作为匿名函数

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

答案 1 :(得分:1)

错误消息表明this为空。原因是反应不会对反应元素进行自动调整this。也就是说,this在调用ask(question)方法时不会引用元素本身。您只需将其绑定在constructorthis.ask = this.ask.bind(this)中即可。您最好阅读official react blog上的ES6课堂笔记。

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