这是通过钩子更新状态的正确方法吗?

时间:2020-04-03 02:49:46

标签: javascript reactjs

首先要对我的英语不好说。

我目前正在申请组织比赛。我有一个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>
  );
}


2 个答案:

答案 0 :(得分:2)

您快到了,正在正确使用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);
}, []);

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

答案 1 :(得分:1)

最好只在组件挂载后才进行api调用:

useEffect(() => {
  getTournaments(props.sport)
}, [props.sport]}