在.map函数中设置React状态而不会覆盖状态

时间:2019-11-07 03:08:05

标签: javascript reactjs javascript-objects setstate array.prototype.map

JavaScript的新手,我正在努力使用一种简单的map方法。

我想遍历两个对象数组,并设置状态以包括每个映射的结果。目前,每个新项目都将覆盖状态。

所需的输出:

refData = {
 user: [
  {key: 1, value: "A"},
  {key: 2, value: "B"}
 ],
 product: [
  {key: 1, value: "A"},
  {key: 2, value: "B"}
 ],
 role: [
  {key: 1, value: "A"},
  {key: 2, value: "B"}
 ]
}

当前输出:

refData = {
 user: [
  {key: 1, value: "A"},
  {key: 2, value: "B"}
 ]
}

refData = {
 product: [
  {key: 1, value: "A"},
  {key: 2, value: "B"}
 ]
}

refData = {
 role: [
  {key: 1, value: "A"},
  {key: 2, value: "B"}
 ]
}

产生当前错误输出的代码:

const [refData, setRefData] = React.useState();

  useEffect(() => {

    const refDataArr = [
      { url: "users", field: "user" },
      { url: "products", field: "product" },
      { url: "roles", field: "role" }
    ]

    const fetchRefData = () => {
      try {
        refDataArr.map(async (o, index) => {
          let url = o.url
          let field = o.field
          const res = await axios.get(`http://.../${url}/ `);
          const data = res.data.data

          const resArr = Object.values(data).map((item, index) => {
            return {
              key: item._key,
              value: item[field]
            }
          });
          setRefData({  //overwritten with each returned item
            ...refData, 
            [field]: resArr, 
          })
        })
      } catch (err) {
        console.log(err);
      }
    }
    fetchRefData();
  }, []);

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

一种方法是先构建json对象,然后将其设置为状态。

  React.useEffect(() => {
    ..........
    let newRefData = {};
    ..........
    try {
      refDataArr.map(async(o, index) => {
          let url = o.url
          let field = o.field
          const res = await axios.get(`http://.../${url}/ `);
          const data = res.data.data

        const resArr = Object.values(data).map((item, index) => {
          return {
            key: item._key,
            value: item[field]
          };
        });
        newRefData[field] = resArr;
      });
      setRefData(newRefData);
    } catch (err) {
      console.log(err);
    }
    ..........
  }, []);