gpt4 book ai didi

javascript - 这是在钩子(Hook) react 中更新状态的正确方法吗?

转载 作者:行者123 更新时间:2023-11-28 16:42:13 25 4
gpt4 key购买 nike

首先,请原谅我的英语不好。

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


最佳答案

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

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

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

关于javascript - 这是在钩子(Hook) react 中更新状态的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61004366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com