【问题标题】:API call in ReactJS and setting response to stateReactJS 中的 API 调用并设置对状态的响应
【发布时间】:2021-06-16 11:59:26
【问题描述】:

我有一个 id 的数组,例如 [123,345,212,232……] 我有一个 Rest API 可以根据 id 响应特定产品。

那么在 ReactJS 中,我将如何遍历数组并获取产品并存储在状态中

我尝试在 useEffect{running once as in componentDidMount} 中执行此操作,但它只将第一个产品存储在数组中。

有没有更好的方法来做到这一点?

我有问题的实际代码是

useEffect(() => {
    const getBought = async () => {
        user.bought.map(async (boughtID) => {
          let bought = await get(`/bought/${boughtID}`, {}, true);
          let boughtDate = bought.createdAt.slice(0, 10);

          bought.products.map(async (pr) => {
            let product = await get(`product/${pr.product}`);
            let quantityBought = pr.quantity;

            setAllBoughts({
              ...allBoughts,
              [boughtDate]: [
                ...(allBoughts.boughtDate || []),
                {
                  product,
                  quantityBought,
                },
              ],
            });
          });
        });
    };
    getBought();
  }, []);

所以我有一个用户,在购买的密钥中有一组购买的 ID...

所以我正在遍历那些购买的钥匙

购买的架构中的产品具有产品 ID 和购买的产品数量(pr.product 和 pr.quantity)。所以我点击 API,并将所有产品保存在状态对象中。

所以 allBoughts 是状态,它是一个对象,其键为(日期),如代码 .createdAt.slice(0,10) 中所示,它为我提供了删除 mongodb 添加的其余内容的日期。

但每次我这样做时,都会发生一些事情。

要么只保存第一项,其余不保存 相同的项目被覆盖 或者页面无限重新加载(尤其是当我尝试从 useEffect 中删除依赖数组时)

【问题讨论】:

  • I tried doing this in useEffect{running once as in componentDidMount} but it only stores the first product in array. 这听起来是正确的方法,它只是有一个错误。请向我们展示您为此编写的代码
  • 你能看到我的代码吗,我已经编辑了帖子

标签: node.js reactjs api express


【解决方案1】:
setAllBoughts({
  ...allBoughts,
  [boughtDate]: [
    ...(allBoughts.boughtDate || []),
    {
      product,
      quantityBought,
    },
  ],
});

allBoughts 是该效果运行时存在的状态。即,它是空状态,还没有结果。因此,每次返回结果时,您都在复制空状态,并向其中添加一个条目。这会删除您的所有结果。

相反,您需要使用最新版本的状态,您可以使用 set state 的函数版本:

setAllBoughts(prevState => {
  return {
    ...prevState,
    [boughtDate]: [
      ...(prevState.boughtDate || []),
      {
        product,
        quantityBought,
      },
    ],
  };
})

【讨论】:

  • 哦,谢谢.. 我在类组件中知道这一点,但不知道这也可以在挂钩中完成
【解决方案2】:

从您所说的来看,在我看来,您正在擦除状态中先前存储的结果(您得到 id 123 的结果,存储它,然后是 345 的结果,存储它并擦除以前的值)。或者你只是没有循环遍历数组。

这里是一个示例,说明如何在useEffect 中多次获取并分配状态中的所有结果。

Codesandbox 上的完整工作示例

export default function App() {
  const ids = useRef([1, 3, 5]);
  const [items, setItems] = useState([]);

  useEffect(() => {
    const promises = ids.current.map((id) => fetchData(id));

    Promise.all(promises).then((responses) => {
      setItems(responses);
    });
  }, []);

  async function fetchData(id) {
    const response = await fetch(
      `https://jsonplaceholder.typicode.com/posts/${id}`
    );
    return response.json();
  }

  return (
    <div className="App">
      {items.map((item) => (
        <div key={item.id}>
          {item.id} - {item.title}
        </div>
      ))}
    </div>
  );
}

【讨论】:

  • 你能看到我的代码吗,我已经编辑了帖子
猜你喜欢
  • 1970-01-01
  • 2021-02-23
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-09
  • 1970-01-01
  • 2019-09-09
相关资源
最近更新 更多