簡體   English   中英

使用來自父組件的數據更新狀態,該狀態是一個數組

[英]updating the state which is an array with the data coming from the parent Component

我有一些來自Parent的數據作為道具,我需要借助來自parent的數據創建一個選項,該選項是一組對象。 這是來自父母的數據作為道具

 `data={
      option1: "First "
      option2: "Second"
      option3: "Third"
      option4: "Fourth"
    }`

我需要創建的內容看起來像這樣,但是在我的狀態下

    `const OPTIONS = [{
         label: 'First',
         value: '1'
       }, {
         label: 'Second',
         value: '2'
        }, {
         label: 'Third',
         value: '3'
        },{
        label:'Fourth',
        value:'4'
       }];`

我在數組中有我的狀態

   `this.state={
             options:[]
      }`

我們真正需要做的是setState的數據來自父對象。在所有答案中,我什么地方都看不到任何setState。

您可以使用地圖

您可以將First, Second and so on保持在數組中,以在輸出中獲取value屬性。

所以這里的想法是循環遍歷data對象的鍵,並檢查indexOf鍵是否在值數組中,我們將其加1(因為數組的索引從0開始),否則,我們將其添加0

 let data={ option1: "First",option2: "Second",option3: "Third",option4: "Fourth" } let values = ['First','Second','Third', 'Fourth'] let op = Object.keys(data).map(e=>{ let val = values.indexOf(data[e]) return { label: e, value: val !==-1 ? val+1 : 0 } }) console.log(op) 

您可以使用Object.entries

 let data={ option1: "First", option2: "Second", option3: "Third", option4: "Fourth" } const options = Object.entries(data).map(arr=> ({ label: arr[1], value: arr[0].replace( /^\\D+/g, '') })) console.log(options) 

希望您的父組件如下所示:

class App extends Component {
  constructor() {
    super();
    this.state = {
      data:  {
      "option1": "First ",
      "option2": "Second",
      "option3": "Third",
      "option4": "Fourth"
    }
    };
  }

  render() {
    return (
      <div>
        <Child data={this.state.data} />
      </div>
    );
  }
}

在Child中,您將以this.props.data的形式獲取數據,將其保持為狀態的可能方法是static getDerivedStateFromProps ,如果需要執行一些副作用,則可以使用componentDidUpdate

以下是子組件:

export default class Child extends React.Component {
  constructor() {
    super();
    this.state = {
      options: []
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
        let { data } = nextProps;
        let options = Object.keys(data).reduce((acc, curr) => {
            return [...acc, { label: data[curr], value: curr.replace( /^\D+/g, '') }]
    }, []);
        //or
        /*
        let options= Object.keys(nextProps.data).map((key, index) => ({label: nextProps.data[key], value: index}))};
        */
        return { options };
  }

  render() {
    return (
    this.state.options.map(item => <p key={item.value}>{item.label}</p>)
    );
  }
}

演示鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM