反应setState在.map()

时间:2019-11-06 21:20:10

标签: javascript arrays react-hooks setstate array.prototype.map

我正在尝试从多个端点动态获取数据并使用React钩子保存到本地状态。当我记录以下内容时,似乎refDataArr中每个项目的状态都被覆盖。

正在正确解析和存储数据,但是我希望refData状态包括所有四个结果,并且不被覆盖。

  useEffect(() => {
    const refDataArr = [
      {
        url: "users",
        field: "user"
      },
      {
        url: "products",
        field: "product"
      },
      {
        url: "roles",
        field: "role"
      },
      {
        url: "locations",
        field: "location"
      }
    ]

    const fetchRefData = () => {
      console.log('Fetching reference data...');
      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

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

结果日志示例(其他日志显示用户,角色等,它们正在被覆盖):

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

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

...etc

所需结果:

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"}
 ],
 location: [
  {key: 1, value: "A"},
  {key: 2, value: "B"}
 ]
}

1 个答案:

答案 0 :(得分:1)

您应该构建所需的对象,然后在其完全构建后使用所需的setRefData

useEffect(() => {
    const refDataArr = [
      {
        url: "users",
        field: "user"
      },
      {
        url: "products",
        field: "product"
      },
      {
        url: "roles",
        field: "role"
      },
      {
        url: "locations",
        field: "location"
      }
    ]
    let newData = {};
    const fetchRefData = () => {
      console.log('Fetching reference data...');
      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

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