【发布时间】:2020-07-18 11:12:55
【问题描述】:
有两个页面 - 主页面包含元素列表,另一个页面包含元素的详细描述。使用 react-router。
<Switch>
<Route exact path="/" component={PokemonCardContainer} />
<Route path="/pokemon/:pokemonName" component={Pokemon} />
</Switch>
在带有列表的主页上,会生成一个请求 api,它返回 20 个元素。此外,当我们到达列表的末尾时,更新了 api 请求 - 加载了另外 20 个项目,等等。
详细描述页面由“我选择你!”按钮实现
<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]);
【问题讨论】:
标签: javascript reactjs api react-router