0

我正在尝试使用 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],
}))
4

1 回答 1

0

prop 中的data键应该是要在. 你上面的代码最终会是这样的:sectionssection

const sections = [
  {title: 'key1': data: 'val1'},
  ...
]

什么时候val[1]是一个字符串。

因此,SectionList迭代data只是一个字符串,以在该部分标题下创建每个项目,因此您得到每个字符。如果val[1]可能是一个字符串或可能是一个字符串数组,那么如果需要,您可以通过将其包装在一个数组中来做正确的事情。

如果您可以控制mainObject创建方式,则可能需要预先包装 val:

const mainObject = {
 "key1": ["val1"],
 "key2": ["val2.0","val2.1"],
 "key3": ["val3"],
}
于 2019-08-23T20:05:07.210 回答