gpt4 book ai didi

javascript - 如何在 native react 中获取 json 数据中的数组值?

转载 作者:行者123 更新时间:2023-11-29 23:06:56 24 4
gpt4 key购买 nike

你好,我正在尝试从服务器呈现获取响应,如下所示

.then(responseData => {
responseData.map(detail => {

let currIndex = -1;
let k = detail.data.curriculum.reduce((acc, curr) => {

if (curr.type === 'section') {
acc.push({
title: curr.title,
content: [],
id: []
})
currIndex += 1
} else {
acc[currIndex].content.push(curr.title);
acc[currIndex].id.push(curr.id);
}

return acc;
}, []);
console.log(k)
this.setState({ k })
});
});

我正在尝试呈现这样的 UI

enter image description here

但我得到的是视频内容的名称将像这样一个接一个地列出

enter image description here

目前我试过的对应代码如下

代码

 <Content padder style={{ backgroundColor: "#f4f4f4" }}>

{this.state.k.map(detail =>

<View style={st.card}>
<View style={st.cardHeading}>
<Text style={st.headingText}>{detail.title}</Text>
</View>

<ScrollView
horizontal
style={st.cardBody}>

<View style={st.videoContent}>
<View style={st.videoImage}>
<MaterialCommunityIcons name="play-circle-outline" size={25} color="#fff" />
</View>
<Text style={st.subheadingText}>{detail.content}</Text>
</View>

</ScrollView>

</View>
)}
</Content

>

this.state.k 中的 json 数据如下。我正在尝试将标题呈现为 headingText 并将内容呈现为 videoContent。请帮我找到一个办法。 enter image description here

最佳答案

看起来您缺少的是实际循环遍历 ScrollView 元素内的 content 或 id 数组。根据您当前的数据结构,我建议您这样做。

<ScrollView
horizontal
style={st.cardBody}
>
{detail.content.map((contentValue, i) => (
<View style={st.videoContent}>
<View style={st.videoImage}>
<MaterialCommunityIcons
name="play-circle-outline"
size={25}
color="#fff"
/>
</View>

<Text style={st.subheadingText}>
Title: { contentValue }
Id: { detail.id[i] }
</Text>
</View>
))}
</ScrollView>

请注意,我在 Text 元素内添加了 id 数组的值,这既是为了说明如何访问它,也是为了说明数据结构使得这个相当麻烦,所以改进该结构可能会更好,可能像这样

.then(responseData => {
responseData.map(detail => {
let currIndex = -1;
const k = detail.data.curriculum.reduce((acc, curr) => {

if (curr.type === 'section') {
acc.push({
title: curr.title,
content: []
})
currIndex += 1

} else {
acc[currIndex].content.push(curr);
}

return acc;
}, []);

this.setState({ k })
});
});

这样你就不必在映射时跟踪数组的索引,可以像这样简单地使用它

  {detail.content.map((curr) => (
...
<Text style={st.subheadingText}>
Title: { curr.title }
Id: { curr.id }
</Text>
...
))}

关于javascript - 如何在 native react 中获取 json 数据中的数组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54589042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com