[更改路由时,使用新的路由参数更新redux状态

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

我目前正在尝试实现通用应用,并且在整个应用中都使用了路由参数。因此,我想将路线参数设置为状态。

我可以使用以下方法对SSR做到这一点...

router.get('/posts/:id', (req, res) => {
  res.locals.id = req.params.id

  const store = createStore(reducers, getDefaultStateFromProps(res.locals), applyMiddleware(thunk));
  const router = <Provider store={store}><StaticRouter location={req.url} context={}><App {...locals} /></StaticRouter></Provider>;      
  const html = renderToString(router);
  const helmet = Helmet.renderStatic();

  res.render('index', {
    content: html,
    context: JSON.stringify(store.getState()),
    meta: helmet.meta,
    title: helmet.title,
    link: helmet.link
  });
});

然后从此处使用id功能将getDefaultStateFromProps置于状态... export function getDefaultStateFromProps({ id = ''} = {}) => ({ id })

这一切都很好,并且将正确的ID设置为redux状态,然后我可以在点击此路由时使用它。

我的问题是,当我在客户端更改路由时,不确定如何从URL更新id的redux状态。

就我对路线的处理而言,我正在使用以下内容:

import React, {Component} from 'react';
import { Switch } from 'react-router-dom';
import Header from './header/';
import Footer from './footer';
import { renderRoutes } from 'react-router-config';

export default class App extends Component {
  render() {
    return (
      <div>
        <Header />
        <Switch>
          {renderRoutes(routes)}
        </Switch>
        <Footer />
      </div>
    );
  }
}

export const routes = [
  {
    path: '/',
    exact: true,
    component: Home
  },
  {
    path: '/posts/:id',
    component: Post,
  } 
  {
    path: '*',
    component: PageNotFound
  }
];

然后使用以下水合剂...

const store = createStore(reducers, preloadedState, applyMiddleware(thunk));

const renderRouter = Component => {
  ReactDOM.hydrate((
    <Provider store={store}>
      <Router>
        <Component />
      </Router>
    </Provider>
  ), document.querySelectorAll('[data-ui-role="content"]')[0]);
};

所以我想知道的是如何更改路线...如何从路线参数更新新的:id的redux状态?

我对如何解决这个问题有点迷茫……感谢您的帮助。

redux react-router react-router-redux
1个回答
0
投票

您需要从路径定义文件中导入routes

import { matchPath } from 'react-router';
import { LOCATION_CHANGE } from 'react-router-redux';

// LOCATION_CHANGE === '@@router/LOCATION_CHANGE';
someReducerFunction(state, action){
  switch(action.type){
    case LOCATION_CHANGE:
      const match = matchPath(action.payload.location.pathname, routes[1]);
      const {id} = match.params;
      // ...
    default:
      return state;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.