如何使用反应路由器保持状态

问题描述:

我有一个带有主 App.js 文件的 React 应用程序,该文件保存我的初始状态.然后我设置了一些路由来浏览我的应用程序.

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 = '/';

然后这会将我们路由到我们的主页.但是,一旦主页呈现,状态就会恢复到 App.js 中详述的初始设置.我不知道为什么一旦我被重新路由到网站的另一部分,状态就不会被维护.鉴于我使用的是 react-router,这是否意味着我需要使用 redux 来处理应用程序的状态?

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?

发生这种情况是因为您正在使用 window 对象而不是 react router 进行重定向.您不需要使用 redux.要使用 react 路由器,您需要使用它的 history 方法.然后在组件内部按如下方式使用它:

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('/');

以下面的react函数组件为例:

For example take the following react functional component:

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

说明:上述组件,从props中解构history,然后用它重定向到登录页面

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

历史api链接:https://reacttraining.com/react-router/web/api/history