繁体   English   中英

尝试使用类组件中的方法更新状态中的道具

[英]Trying to update props in state with method in class component

我正在尝试使用一些 Material UI 组件呈现可关闭的选项卡栏,但在用户想要关闭选项卡时无法实现 onDelete 方法。 我正在传递数据集,一个对象数组,作为一个名为 dataSet 的道具。 我想在用户关闭选项卡但不重新渲染时更新它; 所有选项卡仍会出现。 但是,当我在每次单击时 console.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>
      );
    }
  }

问题是您正在使用道具而不是状态渲染组件。 你的渲染函数应该是这样的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM