【问题标题】:How to access dynamic route parameters when preloading server-side render预加载服务器端渲染时如何访问动态路由参数
【发布时间】:2017-09-09 02:16:15
【问题描述】:

我正在尝试呈现一个动态路由,该路由预加载了通过异步 thunk 获取的数据。

我的组件中有一个静态initialAction 方法需要预加载,并让它们根据需要调用操作。完成所有操作并解决承诺后,我会渲染路线/页面。

我的问题是:如何在静态函数中引用路由参数和/或道具?

这里是相关代码,它将调用可能需要预加载数据的任何 initialAction 函数。

const promises = routes.reduce((promise, route) => {
    if (matchPath(req.url, route) && route.component && route.component.initialAction) {
        promise.push(Promise.resolve(store.dispatch(route.component.initialAction(store))))
    }
    return promise;
}, []);

Promise.all(promises)
.then(() => {
    // Do stuff, render, etc
})

在我的组件中,我有静态的initialAction 函数,它将在商店(来自服务器)和道具(来自客户端)中获取。一种或另一种方式,应该通过 redux/thunk 获取类别。如您所见,我在通过服务器加载时没有传递动态 permalink 属性,因为我无法检索它。

class Category extends Component {

    static initialAction(store, props) {
        let res = store !== null ? getCategory(REACT_APP_SITE_KEY) : props.getCategory(REACT_APP_SITE_KEY, props.match.params.permalink)
        return res
    }

    componentDidMount(){
        if(isEmpty(this.props.category.categories)){
            Category.initialAction(null, this.props)
        }
    }

    /* ... render, etc */
}

最后,这是我正在使用的路线:

import Home from '../components/home/Home'
import Category from '../components/Category'
import Product from '../components/product/Product'
import NotFound from '../components/NotFound'

export default [
    {
        path: "/",
        exact: true,
        component: Home
    },
    {
        path: "/category/:permalink",
        component: Category
    },
    {
        path: "/:category/product/:permalink",
        component: Product
    },
    {
        component: NotFound
    }
]

不完全确定我什至是以“标准”方式执行此操作,但到目前为止,此过程在非动态路由上有效。但是,我有一种感觉,我已经离开基地了 :)

【问题讨论】:

    标签: reactjs redux server-side redux-thunk


    【解决方案1】:

    在服务器上有请求对象,在客户端有位置对象。检查当前环境后,从这些对象中提取 url 参数。

    const promises = routes.reduce((promise, route) => {
        var props = matchPath(req.url, route);
        if ( obj && route.component && route.component.initialAction) {
            promise.push(Promise.resolve(store.dispatch(route.component.initialAction(store, props))))
        }
        return promise;
    }, []);
    

    现在您将在桌面和服务器的 initialAction 中获得 url。您可以从中提取动态路由参数

    【讨论】:

    • 我尝试过这个,对我来说真的很有意义,它会像你描述的那样工作。但是,当我尝试在 initialAction 中 console.log() 新的 url 参数时,我仍然无法访问这些参数。我用我的路线更新了我的问题。从我匹配的路线来看,我应该有一个category 参数可用。知道为什么我不能吗?
    • 在 initialAction 中执行 console.log(props) 时会打印什么?
    • 它应该打印 url。如果是这样,您可以从那里提取参数。
    • 从服务器,我传入req.url。在 initialAction 中,它会逐字打印 url:/category/hats。我觉得我错过了一些非常明显的东西。
    • 一个方便的对象!!!我没有意识到 matchPath 返回了有用的信息。感谢您的所有帮助:)
    猜你喜欢
    • 2020-09-13
    • 2017-01-22
    • 1970-01-01
    • 2020-10-17
    • 2015-04-19
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多