history.push is changing url but not rendering component in react

拥有回忆 提交于 2021-01-28 21:26:14

问题


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.

Here is my code for changing the route

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]);

Here is my code for routes

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>

Here is my store component

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;

回答1:


In Store.js add

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

also, remove router Unnecessary

//<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


来源:https://stackoverflow.com/questions/64534429/history-push-is-changing-url-but-not-rendering-component-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!