如何获取新数据以响应 Redux 的 React Router 更改? [英] How to fetch the new data in response to React Router change with Redux?

查看:18
本文介绍了如何获取新数据以响应 Redux 的 React Router 更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Redux、redux-router 和 reactjs.

I'm using Redux, redux-router and reactjs.

我正在尝试制作一个应用程序,我可以在其中获取有关路线更改的信息,因此,我有以下内容:

I'm trying to make an app where I fetch information on route change, so, I've something like:

<Route path="/" component={App}>
    <Route path="artist" component={ArtistApp} />
    <Route path="artist/:artistId" component={ArtistApp} />
</Route>

当有人进入 artist/ 我想搜索艺术家,然后呈现信息.问题是,这样做的最佳方法是什么?

When someone enters to artist/<artistId> I want to search for the artist and then render the information. The question is, what it's the best way of doing this?

我找到了一些关于它的答案,使用 RxJS 或尝试使用中间件来管理请求.现在,我的问题是,这真的有必要还是只是一种保持架构与反应无关的方法?我可以只从 react componentDidMount() 和 componentDidUpdate() 获取我需要的信息吗?现在我通过在那些请求信息的函数中触发一个动作来实现这一点,当信息到达时组件会重新呈现.该组件有一些属性让我知道:

I've found some answers about it, using RxJS or trying a middleware to manage the requests. Now, my question is, Is this really necessary or just a way to keep the architecture react-agnostic? Can I just fetch the information I need from react componentDidMount() and componentDidUpdate() instead? Right now I'm doing this by triggering an action in those functions that request information and the component re-renders when the information has arrived. The component has some properties for letting me know that:

{
    isFetching: true,
    entity : {}
}

谢谢!

推荐答案

现在,我的问题是,这真的是必要的还是只是一种保持架构与反应无关的方法?我可以只从 react componentDidMount() 和 componentDidUpdate() 获取我需要的信息吗?

Now, my question is, Is this really necessary or just a way to keep the architecture react-agnostic? Can I just fetch the information I need from react componentDidMount() and componentDidUpdate() instead?

您完全可以在 componentDidMount()componentWillReceiveProps(nextProps) 中做到这一点.
这就是我们在 真实世界 示例:

You can totally do that in componentDidMount() and componentWillReceiveProps(nextProps).
This is what we do in real-world example in Redux:

function loadData(props) {
  const { fullName } = props;
  props.loadRepo(fullName, ['description']);
  props.loadStargazers(fullName);
}

class RepoPage extends Component {
  constructor(props) {
    super(props);
    this.renderUser = this.renderUser.bind(this);
    this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this);
  }

  componentWillMount() {
    loadData(this.props);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.fullName !== this.props.fullName) {
      loadData(nextProps);
    }

  /* ... */

}

您可以使用 Rx 变得更复杂,但这完全没有必要.

You can get more sophisticated with Rx, but it's not necessary at all.

这篇关于如何获取新数据以响应 Redux 的 React Router 更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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