问题
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