首页 > 解决方案 > React - Axios 调用发出过多请求

问题描述

我通过制作游戏项目来学习 React 和 Redux。我想通过 API 获取数据(属性),但它会导致太多的请求。猜猜它可以直接在功能性反应组件中放置 axios 调用,但我不知道如何修复它。

function Attributes({ attributes, dispatch }) {
  axios.get(`/api/heroes/1/get-attributes`).then(res => {
    dispatch(AttribAction.set(objectToArray(res.data)));
  });

  return (
    <div className="content">
      {attributes.map((attrib, index) => (
        <div
          key={index}
          className={attrib.id == null ? "attrib-block empty" : "attrib-block"}
        >
          <p>
            <strong>{attrib.name}</strong>: {attrib.value}
          </p>
          <div>
            <button
              className="attrib-button"
              onClick={() => dispatch(AttribAction.increment(attrib.id))}
            >
              +
            </button>
            <button
              className="attrib-button"
              onClick={() => dispatch(AttribAction.decrement(attrib.id))}
            >
              -
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}

标签: javascriptreactjsapireact-reduxaxios

解决方案


将代码放入 useEffect 钩子中,然后传入一个数组作为第二个参数,以指定哪些变量应使其在更改时重复效果。一个空数组表示永远不要重复它。

import React, { useEffect } from 'react';

function Attributes({ attributes, dispatch }) {
  useEffect({
   axios.get(`/api/heroes/1/get-attributes`)
     .then(res => {
       dispatch(AttribAction.set(objectToArray(res.data)));
     });
  }, []);

  // ... etc
}

推荐阅读