【问题标题】:React - Axios call make too many requestsReact - Axios 调用发出过多请求
【发布时间】:2020-01-27 01:32:15
【问题描述】:

我正在通过制作游戏项目来学习 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>
  );
}

【问题讨论】:

    标签: javascript reactjs api react-redux axios


    【解决方案1】:

    您可以使用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)));
                });
        }, [])
    
        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>
        );
    }
    
    

    【讨论】:

      【解决方案2】:

      将代码放在一个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
      }
      

      【讨论】:

        猜你喜欢
        • 2019-10-26
        • 2022-10-08
        • 2021-11-23
        • 2020-09-21
        • 2018-04-25
        • 1970-01-01
        • 1970-01-01
        • 2020-11-07
        • 1970-01-01
        相关资源
        最近更新 更多