在服务器端渲染初始数据检索中访问react-router参数

问题描述 投票:0回答:1

我感觉好像缺少了一些显而易见的东西。 FWIW,我在服务器端使用React,Redux,React-Router,React-Router-Redux绑定和Express。

我正在开发我的第一个通用反应应用程序,大部分情况下一切正常。 我有一个动作“ fetchData”,该动作在服务器上运行,并在最初呈现页面之前解决了诺言,然后客户端检查是否需要获取数据。

所有这一切都按照我的意愿工作。

但是,在呈现页面之前需要访问服务器上路由器中的参数时,我遇到了麻烦。

一个例子是:

http://myapp.com/update/:updateid

如何在初始fetchData操作中正确访问updateid参数? 我已经使用上下文对象在客户端成功完成了此操作,但是我对在哪里执行此操作感到有些困惑。

我可以在传递给RouterContext的renderProps中看到它,我只是不知道如何获取它。 我要使用React-Router还是做一些快递?

(我设法通过下面的代码临时解决了这个问题,但是我知道这确实很糟糕,因此为什么我想正确地做到这一点)

// Grab the requested user from the router / url
const pathname = state.getIn(['routing', 'locationBeforeTransitions', 'pathname']);

// Strip out /update/ from the route string
const updatePath = '/update/';
let pathnameWithoutTrailing = pathname;
if (pathname.endsWith('/') || pathname.endsWith('#') || pathname.endsWith('?')) {
  pathnameWithoutTrailing = pathname.slice(0, -1);
}
requestedUpdate = pathnameWithoutTrailing.substr(updatePath.length);
express reactjs redux react-router universal
1个回答
0
投票

如果我正确理解您的问题。 您可以使用this.props.params.updateId访问容器中的updateId。 您需要将updateId作为参数传递给fetchData操作。 像这样:

componentWillMount() {
    this.props.dispatch(fetchData(this.props.params.updateId))
}
© www.soinside.com 2019 - 2024. All rights reserved.