Javascript 从 React Native 中的数组映射函数动态渲染内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37446029/
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
Render Content Dynamically from an array map function in React Native
提问by Xavier C.
I'm trying to get data from an array and using map function to render content. Look at
我正在尝试从数组中获取数据并使用 map 函数来呈现内容。看着
**{this.lapsList()}**
and the associated
和相关的
**lapsList()**
function to understand what I'm trying to do. The result is nothing is displaying (Views under view, etc.) Here is my simplified code:
功能来了解我正在尝试做什么。结果是什么都没有显示(视图下的视图等)这是我的简化代码:
class StopWatch extends Component {
constructor(props) {
super(props);
this.state = {
laps: []
};
}
render() {
return (
<View style={styles.container}>
<View style={styles.footer}>
<View><Text>coucou test</Text></View>
{this.lapsList()}
</View>
</View>
)
}
lapsList() {
this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
_handlePressLap() {
console.log("press lap");
if (!this.state.isRunning) {
this.setState({
laps: []
})
return
}
let laps = this.state.laps.concat([{'time': this.state.timeElapsed}]);
this.setState({
laps: laps
})
console.log(laps);
}
}
}
回答by Cherniv
Don't forget to return
the mapped array , like:
不要忘记return
映射数组,例如:
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
Reference for the map()
method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
map()
方法参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
回答by Nader Dabit
Try moving the lapsList
function out of your class and into your render function:
尝试将lapsList
函数从类中移到渲染函数中:
render() {
const lapsList = this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
return (
<View style={styles.container}>
<View style={styles.footer}>
<View><Text>coucou test</Text></View>
{lapsList}
</View>
</View>
)
}
回答by Franz Medrano
you forgot the return at the beginning of the function lapsList()
你忘记了函数开头的 return lapsList()
lapsList() {
render(
this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
);
})
);
}
回答by Codemaker
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
You forgot to return the map. this code will resolve the issue.
你忘了归还地图。此代码将解决该问题。