【问题标题】:Why is the variable that's being passed to the child component not being updated?为什么传递给子组件的变量没有被更新?
【发布时间】:2019-01-17 01:14:55
【问题描述】:

我将expandedItem 变量传递给子组件,当应用程序状态发生变化时,它需要更新此变量值并将其重新发送到子组件。目前,当应用程序状态更改但它没有重新发送到子组件时,父组件中的值会更新,因此它仍然具有默认值。有谁知道如何将值重新发送到子组件?

这是我的购物车项目视图(子组件)。 isExpanded 变量需要根据应用状态更改进行更新,以控制哪些视图应该展开和折叠。

render() {
    const isExpanded = this.props.expandedViewId === product.id;

父组件的渲染线:

render() {
     const {isLoading, displayDetails, sortCasesAsc, details, items, expandedItem} = this.props.orderInfo;

这里是expandedItem 变量被传递给子组件的地方:

    <FlatList 
            data={items}
            keyExtractor={(item, index) => item.id.toString()}
            renderItem={({item}) => <CartProductItem product={item} expandedViewId={expandedItem} onExpandClick={(id) => this.expandAndCollapseItems(id)} />}
        />

触发变量更新的函数:

expandAndCollapseItems = (id) => {
    this.props.dispatch(collapseCartItemViews(id));
}

购物车动作功能:

export function collapseCartItemViews(id) {
    return (dispatch, getState) => {
        dispatch({
            type: types.SET_EXPANDED_STATE,
            id: id
        });
    }
}

reducer 函数:

    case types.SET_EXPANDED_STATE:
        const id = action.id;

        return {
            ...state,
            expandedItem: id
        }

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    这里:

    const isExpanded = this.props.expandedViewId = product.id;

    应该是

    const isExpanded = this.props.expandedViewId === product.id;

    【讨论】:

    • 我实际上是想解决这个问题,只是忘记了......但这不会对更新或重新发送的扩展视图 ID 产生影响。之后它甚至没有在子组件中重新评估它应用程序状态更改。 expandViewId 在父组件中设置。
    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多