簡體   English   中英

如何在react js中附加2個不同的數組

[英]How to append 2 different array in react js

我有 1 個處於反應狀態的空數組,用於存儲不同的圖像和視頻。 喜歡,

this.state = {
  imageArray: []
}

現在我從我的 redux 中獲取所有圖像和視頻。 那個數組就像,

fetchDataFromRedux:[{key:01_image, value: 'https://....},{key:02_image, value: 'https://....},{key:01_video, value: 'https://....}]

現在我想將fetchDataFromRedux數組附加到this.state.imageArray 中

目前,我在componentDidUpdate 中這樣做,而prevPropsnewProps不相等,

this.setState({imageArray: [...this.state.imageArray, ...fetchDataFromRedux]})

但是每當添加新圖像或視頻時,數組的長度都會加倍。

使用prevState值設置狀態是否按prevState工作?

this.setState((prevState) => {imageArray: [...prevState.imageArray, ...fetchDataFromRedux]})

當您更新componentDidUpdate的狀態時,我們可以使用Map刪除重復項。

注意:我在更新componentDidMount的狀態時刪除重復項。 你可以在componentDidUpdate上做同樣的事情

 import React from "react"; import ReactDOM from "react-dom"; import { Grid, Row, Col } from "react-flexbox-grid"; class App extends React.Component { constructor(props) { super(props); this.state = { imageArray: [ { key: "01_image", value: "https://...." }, { key: "02_image", value: "https://...." } ] }; } componentDidMount() { const { imageArray } = this.state; const updatedArr = [ { key: "02_image", value: "https://...." }, { key: "03_image", value: "https://...." } ]; const mergeArr = imageArray.concat(updatedArr); const mapArr = new Map(mergeArr.map((item) => [item.key, item])); this.setState({ imageArray: [...mapArr.values()] }); } render() { const { imageArray } = this.state; return ( <Grid> <Row> {imageArray.map((item) => ( <Col>{item.key}</Col> ))} </Row> </Grid> ); } } ReactDOM.render(<App />, document.getElementById("container"));

工作代碼: https : //codesandbox.io/s/react-playground-forked-vxb0s?file=/index.js

快樂編碼!!!

暫無
暫無

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

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