Javascript 尝试使用类组件中的方法更新状态中的道具
我试图使用一些材质UI组件呈现一个可关闭的选项卡栏,但在实现用户想要关闭选项卡时的onDelete方法时遇到了问题。我正在传递数据集,一个对象数组,作为一个称为dataSet的道具。我想在用户关闭选项卡但不重新渲染时更新它;所有选项卡仍然显示。但是,每次单击console.log this.state.dataSet时,我都会看到选项卡被删除。我做错了什么Javascript 尝试使用类组件中的方法更新状态中的道具,javascript,reactjs,tabs,react-props,setstate,Javascript,Reactjs,Tabs,React Props,Setstate,我试图使用一些材质UI组件呈现一个可关闭的选项卡栏,但在实现用户想要关闭选项卡时的onDelete方法时遇到了问题。我正在传递数据集,一个对象数组,作为一个称为dataSet的道具。我想在用户关闭选项卡但不重新渲染时更新它;所有选项卡仍然显示。但是,每次单击console.log this.state.dataSet时,我都会看到选项卡被删除。我做错了什么 class ClosableTabs extends Component { state = { tabIndex: 0
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;
渲染数据集时,使用从道具(从不更改)获得的数组:
render(){
const{value,dataSet,…rest}=this.props;//数据集来自props
返回(
{this.renderTabs(dataSet)}//renderTabs呈现this.props.dataSet
);
}
}
相反,渲染来自您所在州的数据集(您应该为this.props.dataSet和this.state.dataSet使用不同的命名,以避免此类错误):
render(){
const{value,…rest}=this.props;
const{dataSet}=this.state;//数据集现在来自state
返回(
{this.renderTabs(dataSet)}//renderTabs呈现this.state.dataSet
);
}
}
问题是您正在使用道具而不是状态渲染组件。
渲染函数应如下所示:
render() {
const { value, dataSet, ...rest } = this.props;
return (
<TabBar value={this.state.tabIndex} onChange={this.onChange} {...rest}>
{this.renderTabs(this.state.dataSet)}
</TabBar>
);
}
}
render(){
const{value,dataSet,…rest}=this.props;
返回(
{this.renderTabs(this.state.dataSet)}
);
}
}
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>
);
}
}
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>
);
}
}
render() {
const { value, dataSet, ...rest } = this.props;
return (
<TabBar value={this.state.tabIndex} onChange={this.onChange} {...rest}>
{this.renderTabs(this.state.dataSet)}
</TabBar>
);
}
}