javascript - 这是用钩子更新状态的正确方法吗?
问题描述
首先为我糟糕的英语道歉。
我目前正在申请组织比赛。我有一个 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 钩子,但是你需要将你的函数包装在一个 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);
}, []);
这将确保您的效果将在组件安装时运行,并且只会运行一次。你所有的副作用都应该在使用效果中
推荐阅读
- amazon-web-services - 如何在 Grafana 上显示 AWS CodeDeploy 部署
- php - 如何添加像“问题 1 of 10”这样的页面指示器?
- java - 创建通用 API 发布正文请求?
- ios - 在 Swift IOS 中的 webView 顶部添加边距
- canvas - 使用 OGL Flowmap 效果为此 WebGL 设置透明背景?
- tensorflow - 视频地面实况的最佳实践?
- javascript - AgGrid 多组计数
- python - 我怎样才能让python忙等待一个确切的持续时间?
- c# - 导航栏上的标题在 iOS 上不起作用
- amazon-web-services - 访问 AWS RDS 事件订阅中的事件 ID