history.push正在更改URL,但未在react中呈现组件

问题描述

我遇到了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;

解决方法

在Store.js中添加

import {withRouter} from 'react-router';
export default withRouter(Store)

另外,删除不必要的路由器

//<Router>    remove this line
  <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>    and remove this line also
,

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

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

你注意到版本不同,所以安装相同版本的react router

npm i history@4.10.1

纱线

yarn add history@4.10.1