【问题标题】:Using module.exports to expose React class instance使用 module.exports 暴露 React 类实例
【发布时间】:2018-08-13 08:09:31
【问题描述】:

我知道标题可能有点混乱。这是一个代码示例:

//First.js
export default class First extends React.Component {
  constructor(props) {
    super(props);

    module.exports.push = route => {
       this.refs.router.push(route)
    }

    module.exports.pop = () => {
       this.refs.router.pop()
    }
  }

  render() {
    return <Router ref="router"/>
  }
}

然后

//second.js
import { push, pop } from "first.js"

//class instantiation and other code
push("myRoute")

密码笔:https://codepen.io/Stefvw93/pen/bLyyNG?editors=0010

目的是避免使用 react-router 中的 withRouter 函数。因此,请从 react-router 的 browserRouter 组件的单个实例中公开推送/弹出历史功能。它的工作原理是创建对路由器实例的引用 (ref="router"),然后通过执行类似 module.exports.push=this.refs.router.push 之类的操作导出此实例

【问题讨论】:

  • 这是一个问题吗?我说不出来。

标签: javascript reactjs react-router


【解决方案1】:

由于您不能声明任何动态导出,因此导出pushpop 的唯一方法是先导出某种可变容器对象,然后再对其进行修改。例如立即导出一个空对象,并在构造函数中设置其pushpop 属性。

//First.js
export const router = {};

export default class First extends React.Component {
  constructor(props) {
    super(props);

    router.push = route => {
       this.refs.router.push(route)
    };

    router.pop = () => {
       this.refs.router.pop()
    };
  }

  render() {
    return <Router ref="router"/>
  }
}

然后

//second.js
import { router } from "first.js"

//class instantiation and other code
router.push("myRoute")

但是这样做有很大的缺点:

  • 您最终将使用最后呈现的路由器实例
  • 不检查此类实例是否已存在
  • 您不能有多个路由器使用相同的模式

我更愿意在需要路由器的地方写withRouter,因为:

  • 它不受竞争条件的影响——你要么有路由器,要么没有,在这种情况下,你会得到一个很好的错误日志
  • 它清楚地传达了您的意图,并且存在有关 withRouter 的文档
  • 使用众所周知且优雅的 HoC 模式
  • 允许您拥有多个路由器

长话短说,可变的全局状态是不好的,不要这样做。

【讨论】:

    猜你喜欢
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 2012-01-03
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多