简体   繁体   English

React - react-router v6 在类组件中使用 Navigate 并设置状态

[英]React - react-router v6 useNavigate in class component and set state

I have a class component that need to redirect to another page, for this I created this function to decorate the export of the class component in order to have the option of navigate in the state of the component我有一个需要重定向到另一个页面的类组件,为此我创建了这个函数来装饰类组件的导出,以便可以选择在组件状态下导航

import { useNavigate } from "react-router-dom";

export const withNavigate = WrappedComponent => props => {
  const navigate = useNavigate();
  // etc... other react-router-dom v6 hooks

  return (
    <WrappedComponent
      {...props}
      navigate={navigate}
      // etc...
    />
  );
};


I want to set the state to the redirected page and tried to do this with this code我想将状态设置为重定向页面并尝试使用此代码执行此操作

this.props.navigate("/url_to_redirect",{
  state:{
    something:response.data
  }
});

but does not work, which is the proper way to set the state when redirecting?但不起作用,重定向时设置状态的正确方法是什么? also the url_to_redirect has it state defined when the app is mounted as this is rendered from a main component that set the state with a async function of redux thunk so this component have a global state set, my intention when redirecting is to override this state set by redux when the app is mounted in the moment that the redirect is done, is there a way to override this as i am trying or is it better to create another component or refactor the redux logic. url_to_redirect 在安装应用程序时也定义了它的状态,因为这是从一个主要组件呈现的,该组件使用 redux thunk 的异步函数设置状态,所以这个组件有一个全局状态集,我在重定向时的意图是覆盖这个状态集通过 redux 在重定向完成时安装应用程序时,有没有办法在我尝试时覆盖它,或者创建另一个组件或重构 redux 逻辑更好。

export const withNavigate = WrappedComponent => props => { export const withNavigate = WrappedComponent => props => {

Why do you need “WrappedComponent =>”?为什么需要“WrappedComponent =>”?

You first have to import that component:您首先必须导入该组件:

import WrappedComponent from “./components/folder”;

// Then… use it;

export const withNavigate = props => {

    return(
      <WrappedComponent
      {...props}
      //…
      />
    );

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM