How to maintain state using react-router

怎甘沉沦 提交于 2021-01-27 21:44:24

问题


I have a react app with a main App.js file that holds my initial state. I then have some routes setup to navigate around my application.

In one of the routes I have a button which when pressed processes a set state. I know that this works as I've console logged the change in state. However, it then also calls:

window.location.href = '/';

This then routes us to our homepage. However, once the homepage renders the state reverts to its initial setup as detailed in App.js. I don't know why state is not being maintained once I'm rerouted to another part of the website. Given I'm using react-router does this mean I need to use redux to handle the app's state?


回答1:


This is happening because you are redirecting using window object rather than react router. You don't need to use redux. To use react router, you need to use its history method. And then use it as follows, inside a component:

this.props.history.push('/');

For example take the following react functional component:

const LoginButton = ({ history }) => (
  <button onClick={() => { history.push('/login'); }} >
    Log in
  </button>
);

Explanation: The above component, destructures history from props, and then use it to redirect to login page

Link to history api: https://reacttraining.com/react-router/web/api/history



来源:https://stackoverflow.com/questions/52725967/how-to-maintain-state-using-react-router

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