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

查看:32
本文介绍了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)));});返回 (<div className="内容">{attributes.map((attribute, index) => (

dispatch(AttribAction.increment(attrib.id))}>+<按钮className="属性按钮"onClick={() =>dispatch(AttribAction.decrement(attrib.id))}>——

))}

);}

解决方案

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

import React, { useEffect } from 'react';功能属性({属性,调度}){使用效果({axios.get(`/api/heroes/1/get-attributes`).then(res => {dispatch(AttribAction.set(objectToArray(res.data)));});}, []);//... 等等}

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

解决方案

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
}

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆