反应模糊的错误消息:"检查`Constructor`的render方法。"

时间:2016-07-14 19:38:20

标签: javascript reactjs react-jsx jsx

我在客户端使用React来呈现我的应用程序的视图。

当我在浏览器控制台中查看错误报告时,我有时会看到错误 Check the render method of 'Constructor'而不是发生错误的类的正确名称。

例如,我会看到如下消息:

Warning: Each child in an array or iterator should have a unique "key" prop.
Check the render method of `Constructor`. See https://<fb.me>/react-warning-keys for more information.

为什么我的班级名称显示为Constructor?如何让React正确显示班级名称。

其他细节:

  • 目前我使用React.createClass()创建课程(即不是 ES6方式)
  • 我的一些课程是使用https://github.com/clayallsopp/react.backbone中的React.createBackboneClass()创建的,以促进React与我们传统的Backbone模型/馆藏的互动
  • 使用gulpbabel编译我的JSX文件。

2 个答案:

答案 0 :(得分:6)

之所以发生这种情况是因为使用createClass创建的组件没有正确的displayName。将显示名称写入应用程序中的每个组件,您将看到正常的消息。

UPD:

例如:

const SomeComponent = React.createClass({
    displayName: 'SomeComponent',
    ...
    render() {
        ...
    }
});

export default SomeComponent;

答案 1 :(得分:1)

来自React Docs

  

的displayName   string displayName

displayName字符串用于调试消息。 JSX自动设置该值;

试试这个:

var Hello = React.createClass({

  displayName: 'Hello World', // here

  render: function() {
    console.log(this.displayName);
    return <div>Hello {this.props.name}</div>;
  }
});