gpt4 book ai didi

reactjs - react 动态组件列表未正确更新

转载 作者:行者123 更新时间:2023-12-02 09:11:08 24 4
gpt4 key购买 nike

Codesandbox 链接 https://codesandbox.io/s/mjxrz2npzy

我正在创建一个应用程序,用户可以在其中单击“添加计时器”按钮来创建有限数量的自定义倒计时/计数计时器,这些计时器在组件 CustomTimerRow 中定义。每行都有一个图标,如果他们单击它,它将删除计时器。

我有以下包含行列表的父组件:

import React, { Component } from 'react';
import {connect} from 'react-redux';
import CustomTimerRow from './CustomTimerRow';
import AddRow from './AddRow';

const mapStateToProps = state => {
return {customTimers:state.clock.customTimers}
};

class ConnectedCustomTimers extends Component
{
constructor(props)
{
super(props);
this.buildCustomTimers = this.buildCustomTimers.bind(this);
}

buildCustomTimers()
{
let timerList = [];
let index = 0;
if(this.props.customTimers)
{
for(let t of this.props.customTimers)
{
timerList.push(<CustomTimerRow number={index++} timer={t}/>)
}
}
return timerList;
}

render()
{
const elems = this.buildCustomTimers();
const addRow = (this.props.customTimers.length < 8 ? <AddRow/>:<span/>);
return (<div>
{elems}
{addRow}
</div>
);
}

}

const CustomTimers = connect(mapStateToProps, null)(ConnectedCustomTimers);
export default CustomTimers

我的 Redux store 对计时器有以下操作:

    case constants.ADD_CUSTOM_TIMER:
return {...state,customTimers:[...state.customTimers,action.payload]};
case constants.REMOVE_CUSTOM_TIMER:
const newTimers = state.customTimers.slice();
newTimers.splice(action.payload, 1);
return {...state,customTimers:newTimers};

添加行时一切正常,但是当我删除一行时,它总是从列表中删除最后一行,无论我是选择中间的一行进行删除,还是删除第一行。

当我添加日志记录时,一直到 CustomTimers 的渲染,一切看起来都是正确的。 buildCustomTimers 正在返回我希望看到的对象列表。但是一旦返回发生并且 React 执行它的操作,我就会看到不同的结果。

我在这里添加和删除组件是不是错了?我同时使用状态更新和包含父项来确定要显示的内容,但似乎重新呈现更新后的组件列表无法正常工作。

更新:我将代码更新为具有以下内容:

buildCustomTimers()
{
let timerList = [];
let index = 0;
if(this.props.customTimers)
{
for(let t of this.props.customTimers)
{
timerList.push(<li key={index++}><CustomTimerRow key={index++} timer={t}/></li>)
}
}
return timerList;
}

render()
{
const elems = this.buildCustomTimers();
const addRow = (this.props.customTimers.length < 8 ? <AddRow/>:<span/>);
return (<div><ul>
{elems}
</ul>{addRow}</div>
);
}

但这根本没有改变行为,所以我不相信列表和关键答案可能是正确的答案(尽管如果有另一种方法可以不打折)

最佳答案

也许错误出在您的 CustomTimerRow 代码中,但是当您在循环中创建组件列表时,您必须添加一个“键” Prop 。此 key 必须是唯一的。

Lists and Keys

如果你尝试:

<CustomTimerRow number={index++} timer={t} key={t.eventType} />

您会发现它正在运行。由于 t.eventType 不是唯一的,因此这不是您的最终 key ,但这向您展示了 key 的重要性。

关于reactjs - react 动态组件列表未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52150039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com