reactjs - history.push 正在更改 url 但未在反应中呈现组件
问题描述
我正面临 react history.push 的问题。我的代码的逻辑是,当 API 调用完成时,如果响应的登录状态为 false,我想推送到另一个路由。URL 正在更改,但在我刷新页面之前组件不会呈现。
这是我更改路线的代码
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;
解决方案
我知道我的回答迟了,但我会将我的解决方案提供给新用户:
有时只是版本的问题:检查history包的版本是否与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
你注意到版本不同,所以安装相同版本的反应路由器
npm i history@4.10.1
纱
yarn add history@4.10.1
推荐阅读
- java - 使用批处理脚本启动、停止 JAR 文件时出现问题
- django - 搜索一对一的关系
- azure - 警报没有被触发,是否会有任何问题确认警报
- java - 在 JOptionPane 中显示输出时出错
- python - 仅当 django ORM 中的值不是 None 时才包含条件
- python - 使用熊猫根据python上元组的第一部分分组
- sql-server - Microsoft SQL Linux [DBNETLIB][ConnectionOpen (SECDoClientHandshake()).]SSL 安全错误
- firebase - Firebase 实时数据库 - 安全规则
- influxdb - 向 influxdb 发送数据时,telegraf 是否会自动附加时间戳?
- reactjs - 如何在 Expo 中使用保证金?