【问题标题】:React router -- How to send props without query params or Redux?React 路由器——如何在没有查询参数或 Redux 的情况下发送道具?
【发布时间】:2017-10-20 03:40:12
【问题描述】:

我想将数据发送到另一个路由,但不想在查询参数中发送。

我不希望每条路由都有一个新的 store,也不想要一个简单地保存所有路由/参数的 store,与它们的发送/消费位置分开。

是否有一种标准方法可以为即将到来的路线指定道具?

【问题讨论】:

  • 你已经在使用 Redux 或 Flux 模式了吗?
  • 使用 Redux,但我不认为这是应用状态,更像是一个临时变量

标签: reactjs react-router


【解决方案1】:

我在 react-router location api docs 上找到了解决方案。

this.props.router.push({
  pathname: '/view-user',
  state: { userId }
});

这对于插页式、独立的模态页面来说似乎很棒。

如果状态丢失,可能需要指定一个后备,但还没有达到那么远。

if (!this.props.location.state) this.props.router.goBack();

或

const locations = this.props.location.pathname.split('/');
// do something 
this.props.route.push(locations.join('/'));

【讨论】:

  • 正要建议
【解决方案2】:

如果您没有在查询参数中发送信息,那么您可以将其放在也可以与路由关联的其他类型的存储中。

您可以使用您自己的函数包装 router.push() 调用,该函数需要您想要传递的额外对象。比如……

function navigateTo(url, extraData) {
  if (extraData !== undefined) { 
    saveExtraDataForRoute(url, extraData);
  }
  router.push(url);
}

在 react-router 中,有一个与路由关联的 onEnter 属性,用于指定要调用的函数。这个函数中的代码可以检索额外的数据,然后做任何你想做的事情。

function onMyScreenEnter() {
  const extraData = getExtraDataForRoute(url);
  goCrazyNutsWithYourExtraData(extraData);
}

您将提供两个函数 saveExtraDataForRoute() 和 getExtraDataForRoute()。他们可以使用您的商店(例如 Redux)、设置单例对象的值或使用 LocalStorage。但本质上,要保存数据以便稍后通过 URL 检索,您会说:

extraDataStore[url] = extraData;

您可能希望研究的另一件事是使用带有 react-router 的 POST 方法。我没有这样做,并且不确定它的效果如何。这是一个链接:How to Handle Post Request in Isomorphic React + React Router Application

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多