更改方向时如何更改Flatlist的numColumns

问题描述

我创建了函数名称getorientation()并将其放在useEffect上,以便每当旋转设备时,它将重新渲染组件并向我显示设备的方向。

我还创建了变量以使用钩子确定方向

getorientation()

const [orientation,setorientation] = useState("")

const window = useWindowDimensions()
const getorientation = () => {
    if (window.height < window.width) {
        setorientation("LANDSCAPE")
    } else {
        setorientation("PORTRAIT")
    }
    return orientation
}

使用时效果

useEffect(() => {
    getorientation()
})
console.log(orientation)

我的问题是我想在Flatlist(LANDSCAPE)中将numsColumns设置为2,在纵向模式下等于1,但是错误弹出窗口告诉我不能即时更改numColumns。我该怎么办?

这是我的单位列表

<View style={styles.container}>
        <FlatList
            contentContainerStyle={{
                paddingLeft: insets.left,paddingRight: insets.right,}}
            data={dishes.dishes}
            numColumns={orientation == "LANDSCAPE" ? 2 : 1}
            renderItem={({ item,index }) => (
             
                <Tile
                    style={styles.tileItem}
                    key={index}
                    title={item.name}
                    caption={item.description}
                    onPress={() => navigation.navigate('dishdetail_Screen',{ dishId: item.id })} // passing infor from one to another screen
                    // chevron={false}
                    featured
                    imageSrc={{
                        uri: baseUrl + item.image
                    }}
                />
             

            )}
            keyExtractor={item => item.id.toString()} />
    </View>

此令人毛骨悚然的错误 enter image description here

P / s:我是新的React-Native开发人员。感谢所有检查我的问题的人

解决方法

尝试像这样向您的Flatlist添加关键道具,其值就是您的方向:

 <FlatList
            key={orientation} // add key prop here
            contentContainerStyle={{
                paddingLeft: insets.left,paddingRight: insets.right,}}
            data={dishes.dishes}
            numColumns={orientation == "LANDSCAPE" ? 2 : 1}
            renderItem={({ item,index }) => (
             
                <Tile
                    style={styles.tileItem}
                    key={index}
                    title={item.name}
                    caption={item.description}
                    onPress={() => navigation.navigate('Dishdetail_Screen',{ dishId: item.id })} // passing infor from one to another screen
                    // chevron={false}
                    featured
                    imageSrc={{
                        uri: baseUrl + item.image
                    }}
                />
             

            )}
            keyExtractor={item => item.id.toString()} />