React - Axios call make too many requests

旧街凉风 提交于 2020-12-12 05:09:30

问题


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


回答1:


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
}



回答2:


You can use a useEffect hook to run the data fetching.

Passing an empty array as the dependencies means the effect will run only once.

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)));
            });
    }, [])

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



来源:https://stackoverflow.com/questions/58122417/react-axios-call-make-too-many-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!