【问题标题】:Accessing react-router parameters in server side rendering initial data retrieval在服务器端渲染初始数据检索中访问 react-router 参数
【发布时间】:2016-11-06 10:41:53
【问题描述】:

我觉得我错过了一些非常明显的东西。 FWIW,我在服务器端使用 React、Redux、React-Router、React-Router-Redux 绑定和 Express。

我正在开发我的第一个通用 React 应用程序,并且大部分情况下一切都运行良好。我有一个动作“fetchData”,它在服务器上运行并在初始呈现页面之前解析一个承诺,然后客户端检查它是否需要获取数据。

所有这些都按我的意愿工作。

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

一个例子是:

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

如何在初始 fetchData 操作中正确访问 updateid 参数?我已经使用上下文对象在客户端成功地完成了这项工作——但我对在哪里这样做有点困惑。

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

(我设法通过执行以下代码暂时解决了它,但我知道这真的很糟糕,因此我想正确地做到这一点)

// 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】:

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

    componentWillMount() {
        this.props.dispatch(fetchData(this.props.params.updateId))
    }
    

    【讨论】:

    • 我希望服务器运行 API 调用并在数据呈现之前获取数据。让服务器渲染页面,然后让客户端将信息发送到服务器似乎没有任何意义,因为服务器应该能够在客户端甚至知道它之前访问参数。我发布的示例代码有效,因为它在页面呈现之前正确发送 API 请求并且在首次加载时可用,但我知道必须有更好的方法来访问服务器上的路由器道具。
    • 如果我在我的服务器代码中使用 console.log renderProps,我可以看到我想要使用的部分,如下所示: { path: 'update/:updateid', getComponent: [Function: getComponent] } ], params: { updateid: 'jor74n6lsgWHk' }, 所以基本上,我想在服务器端操作中使用该参数,而不必先从客户端获取它
    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2016-03-26
    • 2016-11-17
    • 1970-01-01
    • 2023-04-10
    • 2016-04-03
    相关资源
    最近更新 更多