簡體   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