【问题标题】:Using React Router from a non-react class从非反应类中使用反应路由器
【发布时间】:2020-09-20 13:10:47
【问题描述】:

我的应用程序中有一个管理器类,它只是一个普通的 JS 类,它纯粹是合乎逻辑的,没有视图。我在我的几个组件中使用了它的一个实例。对于其中一项操作,我希望它可以更改基于 React 的应用程序中的路线。我知道我可以向每个组件返回一些东西,然后让组件进行路由,但我想知道是否有办法从我的非反应类中做到这一点。有没有办法传入历史对象并将新路由推送给它?

感谢您的帮助。

编辑:这更像是一个理论/方法问题,但例如: 经理类:

class MyManagerClass {
 constructor() {
    this.data = {...some internal data};
}

doSomething(param) {
    if(this.data[param]) {
        this.data[param]();
    } else {
        //here i'd like to change the route in my react app
    }
}
}

组件:

import React, {useContext, useEffect, useRef, useState} from "react";

const MyComponent = props => {
const myManagerClass = new MyManagerClass();

useEffect(() => {
    myManagerClass.doSomething('param');
}, [props.something]);

return (
    <div>Component</div>
)
}

【问题讨论】:

  • 请分享一些代码,以便人们更好地理解。
  • 它更具理论性,但我添加了一个粗略的例子来说明我所问的问题。

标签: javascript reactjs react-router


【解决方案1】:

至少有 2 个解决方案

解决方案 1:

您可以将历史对象作为组件的参数传递给操作

class Util {

  static someAction(history) {
      history.push('/someurl');
  }
}

然后这样称呼它

const Comp = () => {
   const history = useHistory();
   const someHandler = () => {
       Util.someAction(history);
   }
   ...
}

解决方案 2:

为Router使用自定义历史,然后你可以直接将历史导入到类文件中

history.js

import {createBrowserHistory}  from 'history';
export const history = createBrowserHistory();

像路由器一样使用它

import { Router } from 'react-router-dom';
import { history } from './path/to/history';
...

return (
  <Router history={history}>{/* Routes here */}</Router>
)

然后在你的 Class 文件中

import {history} from '/path/to/history';


class Util {

  static someAction() {
      history.push('/someurl');
  }
}

【讨论】:

  • 好的,谢谢。我认为第二个解决方案是我正在寻找的。我将历史对象作为参数传递,但不喜欢它,因为我从很多地方传递了相同的东西。
  • 谢谢。我选择了答案 2,因为我想在 React 组件之外使用历史。请注意,这里有一个错误(已修复)stackoverflow.com/a/63615753/13408445
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 2020-09-30
  • 1970-01-01
  • 2020-03-02
  • 2019-11-14
  • 2020-11-27
  • 1970-01-01
相关资源
最近更新 更多