【问题标题】:React Redux element not updatingReact Redux 元素未更新
【发布时间】:2017-03-28 10:04:53
【问题描述】:

我有一个 Table 组件,它为项目列表呈现行:

return <Row style={styles.row} key={idx} item={item} onSelect={this.props.onRowSelect}>
    {columns.map((col, idx) => {
        return <Column style={col.style} key={`${item._id}_${col.key}`}
                       width={col.width || this._defaultCellWidth} type={col.type}>
            {_.get(item, col.key)}
        </Column>
    })}
    </Row>

每个项目都有selected:bool 值,绑定到每一行的复选框。

另外,我有一个 HeaderRow,其中包含用于全选的复选框。 通过选中复选框,我调度了一个事件来更新选定的字段。 状态本身已更新,但没有重新渲染。 我的行动是:

if(action.id) 
{
    let index = state.items.findIndex(item => item._id == action.id);
    state.items[index].selected = action.selected;
}
else
{
    state.items.map(e=>e.selected = action.selected);
}

return 
{
    ...state,
    items: state.items
}

编辑: 是不是很好的解决方案:

if(action.id) {
            let index = state.items.findIndex(item => item._id == action.id);
            state.items[index].selected = action.selected;
            return {
                ...state
            }

        }else{
            return {
                ...state,
                items: state.items.map((item, index) => {
                    return Object.assign({}, item, {
                        selected: action.selected
                    })
                })
            }
        }

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    记住all data in the Redux store must be considered immutable ("[a reducer] must never mutate its arguments")。

    您正在改变 state.items 中的项目,并且由于 items 保持相同的对象,Redux 认为它未更改,因此视图不会更新。

    【讨论】:

    • 那么我怎样才能在数组中只设置一项并告诉反应它已更新?
    【解决方案2】:

    只是一个经常发生的常见错误。看看this article,它解释了如何安全地更新每种级别。

    在你的情况下应该是这样的:

    return 
    {
        // Copy the current state
        ...state,
        // Replace the items array with a new version,
        // by creating a new array through the map() call.
        items: state.items.map((item, index) => {
            // This isn't the item in the array we are looking
            // for. So simply return it as is.
            if(index != action.id) {
                return item;
            }
    
            // This is the item to be changed. So copy it and
            // overwrite the selected property.
            return {
                ...item,
                selected: action.selected
            };
        });
    }
    

    【讨论】:

    • 不起作用,因为现在所有的行都在渲染(我在行渲染函数中进行了处理)。所以我猜现在它认为所有的项目都变了。
    • 然后你必须进一步分解你的容器和组件。也许你应该看看this videothis component
    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    相关资源
    最近更新 更多