删除数组中的项目并将视图与react和react redux状态同步

时间:2019-03-10 19:06:22

标签: reactjs react-redux

我想知道在删除数组中的项目时如何正确显示。

目前,我有这个:

enter image description here

我的状态:

enter image description here

当我删除第二项“ test 2”时,我将其显示在屏幕上:

enter image description here

并处于我的状态:

enter image description here

请问如何获得真实的渲染效果(“测试1”和“测试3”)?

在我的组件上,我有这个:

{replies.map((reply, indexReply) => {
return (
    <tr key={indexReply}>
        <td className="text-center">
            <input className="input-quick-reply-text" type="text" maxLength="20" defaultValue={reply.text} onChange={(e) => this.handleChangeText(e, indexReply)}/>
        </td>
        ...
        <td>
            <div className="text-right">
                <div className="circle-button remove-reply" onClick={() => this.deleteItem(indexReply)}>
                    <FontAwesomeIcon icon="minus"/>
                </div>
            </div>
        </td>
    </tr>
)
})}

我在类组件中的功能:

deleteItem = (indexReply) => {
    this.props.removeReply(this.props.indexBucket, this.props.indexBlock, indexReply);
};

在我的减速器中:

case SEQUENCES.REMOVE_REPLY :
        indexBucket = action.indexBucket;
        indexBlock  = action.indexBlock;
        indexReply  = action.indexReply;

        console.log(indexBucket, indexBlock, indexReply);

        return {
            ...state,
            buckets: state.buckets.map((bucket, i) => i === indexBucket ? {
                ...bucket,
                blocks: bucket.blocks.map((block, i) => i === indexBlock ? {
                    ...block,
                    messages: block.messages.map((message, i) => i === 0 ? {
                        ...message,
                        replies: [
                            ...state.buckets[indexBucket].blocks[indexBlock].messages[0].replies.slice(0, indexReply),
                            ...state.buckets[indexBucket].blocks[indexBlock].messages[0].replies.slice(indexReply + 1)
                        ]
                    } : message)
                } : block)
            } : bucket)
        };

我尝试添加“ this.forceUpdate();”在我的deleteItem函数中,但是我有同样的问题...

1 个答案:

答案 0 :(得分:1)

这就是为什么将数组索引用作键是not recommended

您正在使用数组索引作为表行中的关键道具,这样,如果您有一个像["test 1", "test 2", "test 3"]这样的数组,并且更新状态以使其变为["test 1", "test 3"] {{1 key的}}属性仍然是索引1,因此出于性能原因,React使用键1而不是新键来渲染以前渲染的DOM元素。快速解决方案是将"test 3"更改为<tr key={indexReply}>