子组件TodoListUI.js中render函数返回的渲染页面代码包含的LIst组件
{/*index是循环的下标*/}
<List
style={{marginTop: '10px', width: '300px'}}
bordered
dataSource={this.props.list}
renderItem={(item, index) => (
<List.Item onClick={(index) => {this.props.handleItemDelete(index)}}>
{item}
</List.Item>
)}
/>
其中onClick事件触发箭头函数调用父组件传递过来的删除方法, 执行该方法并将index作为参数
父组件中的删除方法
handleItemDelete(index) {
//显示子组件传递过来的index参数
console.log('index ',index);
const action = getItemDeleteAction(index);
store.dispatch(action);
}
出现问题:
点击2时,删除的1, 控制台发现index值没有显示, 子组件并没有传递过来参数.
分析:
对子组件的箭头函数进行简化模拟
//定义一个箭头函数
const renderItem = (item, index) => {
//直接输出传入参数
console.log(index); //1
((index) => {
console.log(index); //undefined
})();
}
renderItem('abc', 1);
onClick触发的箭头函数用一个立即执行的箭头函数模拟.
当执行renderItem函数时, 参数传入, 输出传入参数是1
立即执行的匿名箭头函数声明中需要传入一个参数index, 而调用它的时候没法给匿名函数传入index参数, 因此如果想在箭头函数中使用父级传入的参数, 当前箭头函数的参数就应该为空.
当前箭头函数应该修改为:
(() => {
console.log(index); //1
})();
同理:子组件TodoListUI.js应该修改为
<List.Item onClick={() => {this.props.handleItemDelete(index)}}>
{item}
</List.Item>
不知道以上理解是否正确, 不吝赐教!