正在尝试用类组件中的方法更新处于状态的道具



我试图使用一些Material UI组件来呈现一个可关闭的选项卡栏,当用户想要关闭选项卡时,我在实现onDelete方法时遇到了问题。我将数据集(一个对象数组(作为一个名为dataSet的道具传递。每当用户关闭一个选项卡但不重新渲染时,我想更新它;所有选项卡仍然显示。然而,当我每次单击时都会控制台.log this.state.dataSet时,我会看到选项卡正在被删除。我做错了什么?

class ClosableTabs extends Component {
state = {
tabIndex: 0,
dataSet: this.props.dataSet,
};

onDelete = id => {
this.setState(prevState => {
const updatedDataSet = prevState.dataSet.filter(tab => tab.id !== id);
return {
dataSet: updatedDataSet,
};
}, console.log(this.state.dataSet);
};

renderTabs = dataSet => {
return dataSet.map(data => {
return (
<Tab
key={data.id}
label={
<span>
{data.title}
</span>
<Button
icon="close"
onClick={() => this.onDelete(data.id)}
/>
}
/>
);
});
};
render() {
const { value, dataSet, ...rest } = this.props;

return (
<TabBar value={this.state.tabIndex} onChange={this.onChange} {...rest}>
{this.renderTabs(dataSet)}
</TabBar>
);
}
}
export default Tabs;

这是我使用<ClosableTabs />时作为道具传递的数据集

const dataSet = [
{
id: 1,
title: 'title 1',
},
{
id: 2,
title: 'title 2',
},
{
id: 3,
title: 'title 3',
},
];

当您渲染dataSet时,您使用从props获得的数组(它永远不会改变(:

render() {
const { value, dataSet, ...rest } = this.props; // dataSet comes from props

return (
<TabBar value={this.state.tabIndex} onChange={this.onChange} {...rest}>
{this.renderTabs(dataSet)} // renderTabs renders this.props.dataSet
</TabBar>
);
}
}

相反,呈现来自您的状态的数据集(您应该对this.props.dataSet和this.state.dataSet使用不同的命名来避免这种错误(:

render() {
const { value, ...rest } = this.props;
const { dataSet } = this.state; // dataSet now comes from state
return (
<TabBar value={this.state.tabIndex} onChange={this.onChange} {...rest}>
{this.renderTabs(dataSet)} // renderTabs renders this.state.dataSet
</TabBar>
);
}
}

问题是您使用的是props而不是state来呈现组件。你的渲染函数应该是这样的:

render() {
const { value, dataSet, ...rest } = this.props;

return (
<TabBar value={this.state.tabIndex} onChange={this.onChange} {...rest}>
{this.renderTabs(this.state.dataSet)}
</TabBar>
);
}
}

最新更新