在 React SSR 的组件外部检索 url 参数

Retrieve url param outside of component for React SSR

我有这样一个组件

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { createSelector } from 'reselect';
import { useParams } from 'react-router-dom';
import PodcastActions from '../../store/podcast/podcast.actions';

const selectPodcast = createSelector(
    state => state.podcasts,
    (_, id) => id,
    (podcasts, id) => {
        return podcasts
            ? podcasts.find(podcast => {
                return podcast.id.toString() === id;
            })
            : null;
    });

const Podcast = () => {
    const dispatch = useDispatch();
    const params = useParams();
    const podcast = useSelector(state => selectPodcast(state, params.id));
    useEffect(() => {
        if (!podcast) {
            dispatch(PodcastActions.getPodcastById(params.id));
        }
    }, [dispatch, podcast, params.id]);

    return <h2>{podcast.title}</h2>;
};

//Here I need to get the id
Podcast.serverFetch = PodcastActions.getPodcastById(); //Server side render - this is on refresh of the page

export default Podcast;

所以我需要在组件外部获取 podcastId,以便我的 SSR 能够使用它来获取

const dataRequirements =
        routes
            .filter(route => matchPath(req.url, route)) // filter matching paths
            .map(route => route.component) // map to components
            .filter(comp => comp.serverFetch) // check if components have data requirement
            .map(comp => store.dispatch(comp.serverFetch())); // dispatch data requirement

但是我该怎么做呢?

作为参考,url 看起来像这样 localhost:port/podcasts/:id

我最终更改了 datarequirements 函数,如下所示


app.get("/*", async (req, res) => {
    const context = {};
    const store = createStore();

    const dataRequirements = routes
        .filter(route => matchPath(req.url, route)) // filter matching paths
        .map(route => {
            console.dir(route);
            if (route.component?.serverFetch) {
                const params = {};
                const parts = route.path.split(`/`);
                const routeParts = req.url.split(`/`);
                parts.forEach((part, index) => {
                    if (part.startsWith(`:`)) {
                        params[part.substr(1)] = routeParts[index];
                    }
                });

                return store.dispatch(route.component.serverFetch(params));
            }
        });

//REST OF THE LOGIC TO RENDER REACT SSR

希望这对其他人有所帮助。

作为参考,我的路由构建在如下常量文件中

{
   path: "pathOfRoute",
   exact: true,
   component: ReactComponentReference
}