【问题标题】:SectionList creating a separate renderItem for each character of a stringSectionList 为字符串的每个字符创建一个单独的 renderItem
【发布时间】:2019-08-23 19:42:11
【问题描述】:

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

【问题讨论】:

    标签: reactjs react-native react-native-ios react-native-sectionlist


    【解决方案1】:

    sections 属性中的 data 键应该是要在 section 中呈现的项目列表。你上面的代码最终会是这样的:

    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"],
    }
    

    【讨论】:

    • 谢谢,我已经阅读了几次文档,不敢相信我错过了那个细节。
    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多