history.push正在更改URL,但未在react中呈现组件 [英] history.push is changing url but not rendering component in react
问题描述
我遇到了react history.push的问题.我的代码的逻辑是,当API调用完成时,如果响应中的登录状态为false,我想推送到另一条路由.URL发生了变化,但是直到刷新页面后组件才呈现.
I am facing a problem with react history.push . The logic of my code is, when the API call completes, if the login status in response is false, I want to push to another route. The URL is changing but the component is not rendering until I refresh the page.
这是我更改路线的代码
useEffect(() => {
const getProductsData = async () => {
setIsLoading(true);
const productsData = await fetchProductsApi();
setIsLogin(productsData.data.login);
setProductsArray(productsData.data.data);
setIsLoading(false);
console.log(productsData.data);
if (productsData.data.login === false) {
history.push("/");
}
};
getProductsData();
}, [stock]);
这是我的路线代码
const AuthenticatedRoutes = () => {
return (
<Router>
<BottomNavigationMenu />
<Switch>
<Route path="/add_product" component={AddNewProduct} />
<Route path="/add_image/:id" component={AddImage} />
<Route path="/products" component={Products} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
</Router>
);
};
return (
<Router>
<Switch>
<Route exact path="/" component={Store} />
<Route path="/product_detail" component={ProductDetail} />
<Route path="/signup" component={Signup} />
<Route exact path="/signin" component={SignIn} />
<Route component={AuthenticatedRoutes} />
</Switch>
</Router>
这是我的商店组成部分
import React from 'react';
import styles from "./css/store.module.css"
import SearchIcon from '@material-ui/icons/Search';
const Store = () => {
return (
<div className={styles.container}>
<div className={styles.store_card}>
<h1 className={styles.store_name}>Fliq shop</h1>
<h1 className={styles.store_location}>Location</h1>
</div>
</div>
);
}
export default Store;
推荐答案
我知道我的答案来晚了,但我会将解决方案提供给新用户:
i know that my answer is late but i will give my solution to new users:
有时只是版本问题:检查历史记录软件包的版本是否与React Router历史记录的版本相同
sometimes is just a problem of version : check if the version of the history package is the same as the version of react router history
如果您使用npm:
npm list history
纱线:
yarn list history
对我来说我明白
├─ history@5.0.0
├─ react-router-dom@5.2.0
│ └─ history@4.10.1
└─ react-router@5.2.0
└─ history@4.10.1
您注意到版本不同,因此请安装相同版本的React Router
you notice that the versions differs, so install the same version of react router
npm i history@4.10.1
纱线
yarn add history@4.10.1
这篇关于history.push正在更改URL,但未在react中呈现组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!