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商店为计时器提供以下操作:
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>
);
}
但这并没有改变行为所以我不相信列表和关键答案可能是正确的答案(虽然如果还有另一种方法可以不打折)