首页 > 解决方案 > 如何在反应js中附加2个不同的数组

问题描述

我有 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]})

但是每当添加新图像或视频时,数组的长度就会加倍。

标签: javascriptarraysreactjs

解决方案


当您更新 中的状态时,我们可以使用Map删除重复项componentDidUpdate

注意:我在更新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

编码快乐!!!


推荐阅读