我正在尝试使用 SectionList 打印对象的键/值对。但是,作为字符串的值由 renderItem 逐个字符呈现。
代码:
const mainObject = {
"key1": "val1",
"key2": ["val2.0","val2.1"],
"key3": "val3",
}
const renderItem = ({item}) => <Text>{item}</Text>
const sectionHeader = ({section}) => (
<Text style={{fontWeight: "bold"}}>{section.title}</Text>);
//Object.entries(obj) returns an array [["key0","value0"],["key1","value1"]
//for all the key value pairs in the object
const sections = (obj) => Object.entries(obj).map((val) => ({
data: val[1],
title: val[0],
}))
const ObjectList = props => (
<SectionList
renderItem={renderItem}
renderSectionHeader={sectionHeader}
sections={sections(mainObject)}
keyExtractor={(item, index) => item + index}
>
</SectionList>
)
屏幕上的输出是:
key1
v
a
l
1
key2
val2.0
val2.1
key3
v
a
l
3
为了解决这个问题,我已将字符串放入数组中,因此数组中的字符串可以正确打印,但我只是想知道为什么它们需要嵌套在数组中才能将整个字符串打印在一行上?
const sections = (obj) => Object.entries(obj).map((val) => ({
//checks if the value is an array, if not then nest that value
//inside the array otherwise leave it as it is
data: !Array.isArray(val[1]) ? [val[1]] : val[1],
title: val[0],
}))