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

Fra*_*sso 48 javascript reactjs react-router redux

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

我正在尝试创建一个应用程序来获取路由更改的信息,所以,我有类似的东西:

<Route path="/" component={App}>
    <Route path="artist" component={ArtistApp} />
    <Route path="artist/:artistId" component={ArtistApp} />
</Route>
Run Code Online (Sandbox Code Playgroud)

当有人进入时,artist/<artistId>我想搜索艺术家,然后呈现信息.问题是,这是最好的方法吗?

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

{
    isFetching: true,
    entity : {}
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Dan*_*mov 60

现在,我的问题是,这真的是必要的还是仅仅是一种保持架构反应不可知的方法?我可以从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);
    }

  /* ... */

}
Run Code Online (Sandbox Code Playgroud)

使用Rx可以获得更复杂的功能,但根本没有必要.

  • @VictorSuzdalev当然,Redux在这里没有任何意见. (5认同)
  • OMG同样的Dan回答,谢谢老兄!我喜欢你的工作.(对不起,我是一个技术团队) (5认同)

Vic*_*lev 19

我已经用普通路由器onEnter/onLeave回调道具上的自定义绑定做到了这样:

const store = configureStore()

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

它有点hacky但有效,我现在还不知道更好的解决方案.

  • react-router-4 上不再存在 onEnter (2认同)