小编典典

如何通过Redux响应React Router的更改来获取新数据?

reactjs

我正在使用Redux,redux-router和reactjs。

我正在尝试制作一个用于获取路线更改信息的应用程序,因此,我遇到了一些类似的问题:

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

当有人进入时,artist/<artistId>我想搜索艺术家,然后渲染信息。问题是,这样做的最佳方法是什么?

我已经找到了有关此问题的答案,使用RxJS或尝试使用中间件来管理请求。现在,我的问题是,这真的必要吗?还是保持体系结构不可知的一种方法?我可以直接从react
componentDidMount()和componentDidUpdate()获取我需要的信息吗?现在,我正在通过在那些请求信息的功能中触发一个动作来执行此操作,并且在信息到达时组件会重新渲染。该组件具有一些让我知道的属性:

{
    isFetching: true,
    entity : {}
}

谢谢!


阅读 276

收藏
2020-07-22

共1个答案

小编典典

现在,我的问题是,这真的必要吗?还是保持体系结构不可知的一种方法?我可以直接从react
componentDidMount()和componentDidUpdate()获取我需要的信息吗?

您可以在componentDidMount()和中完全做到这一点componentWillReceiveProps(nextProps)
这是我们在Redux 中的real- world示例中所做的:

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可以使功能更加完善,但这完全没有必要。

2020-07-22