反应-Axios调用发出太多请求 [英] React - Axios call make too many requests

查看:88
本文介绍了反应-Axios调用发出太多请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习React&通过制作游戏项目来实现Redux.我想通过API提取数据(属性),但这会导致过多的请求.猜猜可以将axios调用直接放置在功能性react组件中,但是我不知道如何解决.

Im learning React & Redux by making a game project. I want to fetch data (attributes) by API, but it cause too many requests. Guess it can be realted to placing axios call directly in functional react component, but i have no idea how to fix it.

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>
  );
}

推荐答案

将代码放入useEffect挂钩中,然后将数组作为第二个参数传递,以指定如果变量发生变化,哪些变量将导致其重复执行效果.空数组表示永不重复.

Put the code in a useEffect hook, and then pass in an array as the second parameter to specify what variables should cause it to repeat the effect if they change. An empty array says never to repeat it.

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
}

这篇关于反应-Axios调用发出太多请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆