【问题标题】:Update redux state with new route params when route changes路由更改时使用新的路由参数更新 redux 状态
【发布时间】:2020-09-05 10:25:36
【问题描述】:

我目前正在尝试实现一个通用应用程序,并在整个应用程序中使用路由参数。因此,我想将路由参数置于状态。

我可以使用以下方法为 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 = ''} = {}) =&gt; ({ 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】:

    您需要从路由定义文件中导入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;
      }
    }
    

    完整的工作示例: https://codesandbox.io/s/elegant-chaum-7cm3m?file=/src/index.js

    【讨论】:

    • LOCATION_CHANGE 操作是如何被触发的?
    • 路由库自动触发。
    • 我正在使用 redux 开发工具,但似乎永远看不到动作调度?我使用 react-router v4 进行设置...这仍然可以使用吗?
    • 是的,它确实适用于 v4。您可能缺少一些额外的设置。我用一个完整工作示例的链接更新了答案。
    • 刚刚开始工作...非常感谢您的帮助和演示
    猜你喜欢
    • 2016-10-21
    • 2016-11-26
    • 2018-01-05
    • 2022-10-04
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 2021-04-26
    • 2020-04-26
    相关资源
    最近更新 更多