Javascript 通过带有对象子项的数组来反应本机映射-与反应网络中的工作方式不同吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35286175/
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
React native mapping through array with object childs - working different as in react web?
提问by noa-dev
I have this array which contains objects:
我有这个包含对象的数组:
var tmp_array = [
{ headline: "Test", text: "Test text", send_at: "test date" }
];
Now in the web react environment I was able to map through this array and return its values to a variable which can then be rendered.
现在在 web react 环境中,我能够映射这个数组并将它的值返回到一个变量,然后可以渲染。
So I used the same approach:
所以我使用了相同的方法:
var i = -1;
var WholeNews = tmp_array.map(function(news){
i++;
return(
<View key={i}>
<Text>{news.headline}</Text>
<View>
<Text>{news.text}</Text>
</View>
</View>);
});
After the mapping has finished it should be rendered as following:
映射完成后,它应该呈现如下:
return(
<View>
{WholeNews}
</View>
);
Unfortunately I receive a warning in my iOS Simulator which says:
不幸的是,我在 iOS 模拟器中收到一条警告,内容为:
Objects are not valid as a React child(found: object with keys {WholeNews}). If you meant to render a collection of children, use an array instead or wrap the object using createFrament(object) from the React-addons.
对象作为 React 子对象无效(找到:带有键 {WholeNews} 的对象)。如果您打算渲染一组子项,请改用数组或使用 React 插件中的 createFrament(object) 包装对象。
I am not sure whether I am missing out something completely or react native simply doesn't support a mapping through an array as in my example.
我不确定我是完全遗漏了某些东西,还是本机反应根本不支持通过数组进行映射,如我的示例所示。
回答by Samuli Hakoniemi
This should work:
这应该有效:
WholeNews() {
return tmp_array.map(function(news, i){
return(
<View key={i}>
<Text>{news.headline}</Text>
<View>
<Text>{news.text}</Text>
</View>
</View>
);
});
}
render() {
return(
<View>
{this.WholeNews()}
</View>
)
}