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

IT技术 javascript reactjs react-router redux
2021-04-09 22:58:40

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

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

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

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

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

{
    isFetching: true,
    entity : {}
}

谢谢!

3个回答

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

你完全可以在componentDidMount()和 中做到这一点componentWillReceiveProps(nextProps)
这就是我们在 Reduxreal-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 变得更复杂,但这根本没有必要。

在 React Router 中使用 onEnter/onLeave 道具是“惯用的 Redux”吗?
2021-05-22 22:58:40
@VictorSuzdalev 当然,Redux 在这里没有意见。
2021-05-25 22:58:40
我被困了,因为 componentWillMount 和 componentWillReceiveProps 现在已弃用 😀
2021-05-29 22:58:40
天哪,同样的丹回答,谢谢老兄!我喜欢你的工作。(抱歉,我是个技术爱好者)
2021-06-21 22:58:40

我在普通路由器 onEnter/onLeave 回调props上使用自定义绑定做到了这一点,如下所示:

const store = configureStore()

//then in router
<Route path='/myRoutePath' component={MyRouteHandler} onEnter={()=>store.dispatch(myRouteEnterAction())} />

这有点hacky但有效,我现在不知道更好的解决方案。

react-router-4 上不再存在 onEnter
2021-06-01 22:58:40
这是一个很好的选择(大多数时候我更喜欢)。如果你想让你的组件愚蠢到不知道如何获取数据,这就是你的方法。我喜欢组件只对 props 变化进行渲染和“反应”。相反,如果组件作为一种状态,涉及到对应用程序的其余部分不透明的 API 调用(例如:您在 npm 上发布的 github 星计数器),那么 componentWillMount () => loadData 更有意义。干杯!
2021-06-14 22:58:40
@FrancoRisso 只是一个品味问题,不要在这里争论 ))))
2021-06-20 22:58:40
感谢您的解决方案!它有效,虽然我更喜欢 Dan 的方法将事物保存在同一个组件中,但我认为它更干净。
2021-06-21 22:58:40

1)在路由改变时分派乐观请求动作,即 BrowserHistory.listen(location => dispatch(routeLocationDidUpdate(location)));

2)异步操作:http : //redux.js.org/docs/advanced/AsyncActions.html