首页 > 解决方案 > 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;

标签: reactjsroutesreact-routerreact-router-domhistory

解决方案


我知道我的回答迟了,但我会将我的解决方案提供给新用户:

有时只是版本的问题:检查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

推荐阅读