簡體   English   中英

React - Axios 調用發出太多請求

[英]React - Axios call make too many requests

我通過制作游戲項目來學習 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>
  );
}

將代碼放入 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
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM