【问题标题】:memo doesn't detect the changes in the props pass into the component备忘录没有检测到传递给组件的道具的变化
【发布时间】:2020-03-28 16:50:16
【问题描述】:

我正在使用来自 Apollo GraphQL 的 useMutation 钩子,我想使用 onCompleted 属性执行某个任务。基本上,我想在useMutation 成功完成时执行setCheck() 钩子,并将check 状态作为道具传递给子组件

const ParentComponent = () => {
    const [ check, setCheck ] = useState(false)
    const [ createMessage, { loading } ] = useMutation(CREATE_MESSAGE_MUTATION, {
        onCompleted: data => {
            setCheck(true)
        },
        onError: data => {
            console.log("onError Mutation", data)
        }
    })

    return (
        <KeyboardAvoidingView>
            <FlatList 
                data={messages}
                renderItem={({ item }) => 
                    <ChildComponent 
                        item={item} 
                        check={check}
                    />
                }
                keyExtractor={item => item.id.toString()}
            />
        </KeyboardAvoidingView>
    )
}

问题是每次父组件渲染时ChildComponent 渲染次数太多,所以我使用memo 解决了不必要的重新渲染:

const ChildComponent = ({check}) => {
    console.log("check", check)
    return (
        <View style={styles.container} >

        </View>
    )
}

export default React.memo(ChildComponent)

但是,memo 不知何故没有检测到状态 check 的变化,并且根本不渲染组件。为什么memo没有详细说明传入的props的变化,有没有办法监听变化?

【问题讨论】:

    标签: javascript reactjs react-native graphql react-apollo


    【解决方案1】:

    问题在于FlatList - 只有在其data 发生变化时才会重新渲染其子级。由于renderItem 依赖于check,它不是data 的一部分,因此您需要将其包含在extraData 属性中,以便在check 更改时重新渲染项目。有关示例,请参阅文档:https://facebook.github.io/react-native/docs/flatlist#basic-example

    所以你的FlatList 组件应该是:

                <FlatList 
                    data={messages}
                    renderItem={({ item }) => 
                        <ChildComponent 
                            item={item} 
                            check={check}
                        />
                    }
                    keyExtractor={item => item.id.toString()}
                    extraData={check}
                />
    

    【讨论】:

      【解决方案2】:

      check 不是状态的一部分,它是道具的一部分。尝试将其传递给 useState 钩子以使组件有状态

      【讨论】:

        猜你喜欢
        • 2020-09-28
        • 2019-04-24
        • 1970-01-01
        • 2019-02-26
        • 1970-01-01
        • 2019-11-12
        • 1970-01-01
        • 2021-08-14
        • 1970-01-01
        相关资源
        最近更新 更多