有人可以解释共享可以跟踪 Redux 状态的 URL 的最佳方式是什么吗? [英] Can someone explain what is the best way to share an URL that can keep track of the Redux state?

查看:33
本文介绍了有人可以解释共享可以跟踪 Redux 状态的 URL 的最佳方式是什么吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解如何在共享 URL 时保持当前状态.

I'm having hard times understanding how I can keep the current state when sharing an URL.

我有一个用 React 和 Redux 制作的应用.

I have an app made with React and Redux.

  1. 当我点击一个按钮时,我正在调度一个动作来更新商店,同时我正在改变路线.
  2. Redux 存储得到更新,组件使用来自 Redux 存储的数据进行渲染.
  3. 如果我想将 URL 分享给拥有相同应用的人,则该人不会更新商店,因此不会呈现任何内容.

我试着总结一下代码:

on route: /
  <Home>
    <BookList data={featured} />
    <BookList data={top} />
  </Home>

on route: /record/:recid
  <BookDetails>
    <BookInfo />
    <BookList data={suggested}/>
  </BookDetails>    

BookList is a reusable component:
<BookList>
  <BookItem onCLick={goToDetailsPage}/>
  <BookItem />
  <BookItem />
  <BookItem />
</BookList>

我该如何解决这个问题?

How can I solve this issue?

感谢您提供的所有帮助!

Thank you for all the help you can provide!

推荐答案

为了将正确的状态加载到模型视图(书籍)中,您需要访问必要的变量.实现此目的的两种简单方法是通过 url 参数 ?recid=12 或使用 react-router 的匹配参数,您正在此处执行此操作.您可以通过路由 match.params.recid 访问 :recid.

In order to load the correct state to your model view (book), you'll need to have access to the necessary variables. Two simple ways to achieve this is through a url param ?recid=12 or using react-router's match params, which you're doing here. You have access to the :recid through the route match.params.recid.

React 文档建议在 componentDidMount() 中获取数据,但是当您的路径更新时,在 componentDidUpdate() 中获取新数据没有任何问题.请记住跟踪您的获取状态,因此您不会进行多次 api 调用.淡化版本可能如下所示:

React docs recommend fetching data in componentDidMount(), but there's nothing wrong with fetching new data in componentDidUpdate() when your path updates. Remember to keep track of your fetching state, so you don't make multiple api calls. A watered down version could look something like this:

class BookModel extends Component {
  constructor {...}

  componentDidMount() {
    const { dispatch, match } = this.props;
    const { recid } = match.params;

    dispatch(someFetchAction("book", recid));
  }

  componentDidUpdate(prevProps) {
    const { dispatch, fetching, match } = this.props;
    const oldBook = prevProps.match.params.recid;
    const newBook = match.params.recid;
    const didUpdate = oldBook !== newBook;

    //fetch new record if not already fetching and record id has changed
    !fetching && didUpdate && dispatch(someFetchAction("book", newBook));
  }

  render() {...}
}

export default connect((store, props) => ({
  bookModels: store.bookModels,
  fetching: store.fetching
}))(BookModel);

如果您遇到更新未发生的问题,您可能需要添加 withRouter,但我认为在这种情况下没有必要.

If you're experiencing issues with updates not happening, you may want to add withRouter, but I don't believe it would be necessary in this case.

这篇关于有人可以解释共享可以跟踪 Redux 状态的 URL 的最佳方式是什么吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆