gpt4 book ai didi

javascript - 按下后退按钮时防止 react 路由器重新加载 API 调用。 react 堆

转载 作者:行者123 更新时间:2023-12-05 07:10:54 26 4
gpt4 key购买 nike

有两个页面 - 包含元素列表的主页面和包含元素详细描述的页面。使用 react 路由器。

<Switch>
<Route exact path="/" component={PokemonCardContainer} />
<Route path="/pokemon/:pokemonName" component={Pokemon} />
</Switch>

在带有列表的主页上,生成了一个请求 api,它返回 20 个元素。此外,当我们到达列表末尾时,将更新 api 请求 - 加载另外 20 个项目等。enter image description here

详细描述页面由“我选择你!”按钮实现

<Link to={`pokemon/${pokemonName}`}>
{pokemonName}, I Choose You!
</Link>

在详细描述页面上有一个按钮“返回首页”

const handleGoToHomePage = () => {
props.history.push({
pathname: "/",
});
};

相应地,当我按下返回到主页时,一个新的 api 请求发生了,我到达了页面的顶部。但我需要返回到我单击的列表元素。例如,如果我点击了第 60 个元素,我需要返回到它。我明白我需要在返回main时中断api请求?

      /* States */
const [pokemons, setPokemons] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const [currentPage, setCurrentPage] = useState(
"https://pokeapi.co/api/v2/pokemon"
);
const [nextPage, setNextPage] = useState("");
const [hasMore, setHasMore] = useState(false);
useEffect(() => {
let cancel;
const fetchData = () => {
setLoading(true);
setError(false);
Axios({
method: "GET",
url: currentPage,
cancelToken: new Axios.CancelToken((c) => (cancel = c)),
})
.then((res) => {
setPokemons((prevPokemons) => {
return [...prevPokemons, ...res.data.results];
});
setNextPage(res.data.next);
setHasMore(res.data.results.length > 0);
setLoading(false);
})
.catch((error) => {
if (Axios.isCancel(error)) return;
setError(true);
});
};
fetchData();
return () => cancel();
}, [currentPage]);

最佳答案

我看到了两种可能性,

您在未卸载的父组件(例如菜单或主要组件)中进行 API 调用

或者您使用类似 Redux 的方式将数据保存在存储中.如果您的应用很复杂并且需要处理组件之间共享的复杂状态,我会选择此选项。

关于javascript - 按下后退按钮时防止 react 路由器重新加载 API 调用。 react 堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61060072/

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