Javascript 必须返回有效的 ReactComponent。您可能返回了未定义、数组或其他无效对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34800809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object
提问by Radu033
I'm building a small react js application and I get this error:
我正在构建一个小型 react js 应用程序,但出现此错误:
Uncaught Error: Invariant Violation: exports.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.
未捕获的错误:不变违规:exports.render():必须返回有效的 ReactComponent。您可能返回了 undefined、数组或其他一些无效对象。
These are my source files: App.jsx
这些是我的源文件:App.jsx
var React = require('react');
var Chats = require('./chats');
var messages = {
chatMessages: [{
name: ' John Doe',
message: ' Hey Lisa, how are you doing?'
},{
name: 'Lisa Johnson',
message: 'Pretty good, how are you?'
}]
}
var App = React.createElement(Chats, messages)
React.render(App, document.querySelector('.container'));
Chats.jsx
Chats.jsx
var React = require ('react');
var Chat = require ('./chat');
var Chats = React.createClass({
render:function(){
var chats = this.props.chatMessages.map(function(chatProps){
return <Chat {...chatProps} />
});
return (
<div>
{chats}
</div>
)
}
});
module.exports = Chats;
And Chat.jsx
和Chat.jsx
var React = require ('react');
var Chat = React.createClass ({
render:function (){
return
<div>
<p>{this.props.name}</p>
<span> {this.props.message} </span>
</div>
}
});
module.exports = Chat;
I think the problem is in my map function but I really want someone to tell me where I made the mistake.
我认为问题出在我的地图功能上,但我真的希望有人告诉我我在哪里犯了错误。
回答by Josh David Miller
I downloaded your code from GitHub. The problem was, as I suspected, wrapping components in parentheses on the return
. From your updated code above, you did not do this on the Chat
component. This is necessary because the transformed value of React.createElement
will reside on the nextline after the return
, never actually running. Here's the altered function:
我从 GitHub 下载了你的代码。正如我所怀疑的,问题是将组件包装在return
. 从上面更新的代码中,您没有在Chat
组件上执行此操作。这是必要的,因为转换后的值React.createElement
将驻留在 之后的下一行return
,永远不会实际运行。这是更改后的功能:
var Chat = React.createClass({
render: function () {
return (
<div>
<p>{this.props.name}</p>
<span> {this.props.message} </span>
</div>
);
}
});
Also, for what it's worth, your App
component is redundant. You could just do this:
此外,就其价值而言,您的App
组件是多余的。你可以这样做:
React.render( <Chats {...messages} />, document.querySelector( '.container' ) );