首页 > 解决方案 > 这是用钩子更新状态的正确方法吗?

问题描述

首先为我糟糕的英语道歉。

我目前正在申请组织比赛。我有一个 ListTournament 组件,它根据运动 (prop.sport) 显示组件。我正在做的是在创建组件时调用 axios ,这样做会产生一个无限循环,我通过仅在将新运动选择为前一个运动时更新状态来解决此问题。

这是正确的方法吗?


import React,{useEffect,useState} from "react";
import Tournament from "./Card";
import "../resources/styles/grid.css";
const axios = require("axios").default;

var selected_sport = ''

export default function ListTournaments(props) {
const [tournaments,setTournaments] = useState([])

  const getTournaments = sport => {
    axios
      .get("https://futbol-back.herokuapp.com/tournaments/sport/" + sport)
      .then(function(response) {
        // handle success
        // tournaments = response.data;
        if (props.sport!= selected_sport){ // This is where I correct the infinite loop
          console.log(selected_sport)
          selected_sport = props.sport
          setTournaments(response.data)

        }
      })
      .catch(function(error) {
        // handle error
        console.log(error);
      })
      .then(function() {
        // always executed
      });
  };

getTournaments(props.sport)

  return (
    <div className="tournamentsWrapper">
      {tournaments.map((tournament, index) => (
        <Tournament
          title={tournament.title}
          description={tournament.description}
          requierements={tournament.requierements}
          date={tournament.date}
          img={tournament.img}
          key={index}
        />
      ))}
    </div>
  );
}


标签: javascriptreactjs

解决方案


你快到了,你正在正确使用 useState 钩子,但是你需要将你的函数包装在一个 useEffect 钩子中,因为你是。产生副作用。

useEffect(() => {
  const getTournaments = async (sport) => {
   axios
   .get("https://futbol-back.herokuapp.com/tournaments/sport/" + sport)
   .then(function(response) {
    // handle success
    // tournaments = response.data;
    if (props.sport!= selected_sport){ // This is where I correct the infinite loop
      console.log(selected_sport)
      selected_sport = props.sport
      setTournaments(response.data)

    }
  })
  .catch(function(error) {
    // handle error
    console.log(error);
  })
  .then(function() {
    // always executed
  });
};

 getTournaments(props.sport);
}, []);

这将确保您的效果将在组件安装时运行,并且只会运行一次。你所有的副作用都应该在使用效果中


推荐阅读