【问题标题】:React-router dynamic route with dynamic action具有动态动作的 React-router 动态路由
【发布时间】:2017-12-15 17:58:12
【问题描述】:

了解您可以使用以下方法创建动态路由:

<Route path="/:category" component={PostsContainer} />

class PostsContainer extends Component {
  render() {
    <p>{this.props.match.params.category}</p>
  }
}

所以我的问题是如何通过 api 调用向调度添加动态路由?

我想做一些事情,比如在 a 类中,向 a 类发送 api 调用,然后派发……而在 b 类中,向 b 类发送 api 调用,然后派发……

export const getPostsAction = (match) => (dispatch) => {
  getPosts(category).then((posts) => {
    dispatch({
      type: postsConst.GET_ALL_POSTS_SUCCESS,
      posts,
    });
  });
};

问题是我不能将 componentDidMount 与 this.props.getPostsAction(category) 一起使用,它只会发生一次,即使我点击不同的 /categories... 或者我应该从 componentWillRecieveProps 更新,但我是不太确定什么是最好的方法...

【问题讨论】:

  • API 调用 A 类与 B 类有何不同
  • 你能举一个你想要调度的动作类型的例子吗?它有什么动态?
  • 添加了动作。所以 getPosts 会有类似 /api/category/${category}
  • 你知道我半小时前把这个放在我的回答里了 :)

标签: reactjs react-router react-redux react-router-v4


【解决方案1】:

编辑:解决您的编辑问题 - 随时在componentWillReceiveProps 发送您的操作this.props.match.params.category !== nextProps.match.params.category

这应该有效;提供postsConst 已定义。

export const getPostsAction = (match) => (dispatch) => {
    return getPosts(`/api/category/${match.params.category}`).then(posts => {
        dispatch({
            type: postsConst.GET_ALL_POSTS_SUCCESS,
            posts,
        });
    });
};

您还可以在 return 语句之前分派一个操作,以便您的应用程序知道它当前正在获取数据。类似:dispatch({type: "IS_FETCHING_POSTS"}),当然您需要一个减速器来执行该操作。

如果您需要有关 redux 中异步操作的更多信息,请查看 Async Actions Documentation

这是文档中提供的示例:

export function fetchPosts(subreddit) {
  // Thunk middleware knows how to handle functions.
  // It passes the dispatch method as an argument to the function,
  // thus making it able to dispatch actions itself.

  return function (dispatch) {
    // First dispatch: the app state is updated to inform
    // that the API call is starting.

    dispatch(requestPosts(subreddit))

    // The function called by the thunk middleware can return a value,
    // that is passed on as the return value of the dispatch method.

    // In this case, we return a promise to wait for.
    // This is not required by thunk middleware, but it is convenient for us.

    return fetch(`https://www.reddit.com/r/${subreddit}.json`)
      .then(
        response => response.json(),
        // Do not use catch, because that will also catch
        // any errors in the dispatch and resulting render,
        // causing a loop of 'Unexpected batch number' errors.
        // https://github.com/facebook/react/issues/6895
        error => console.log('An error occurred.', error)
      )
      .then(json =>
        // We can dispatch many times!
        // Here, we update the app state with the results of the API call.

        dispatch(receivePosts(subreddit, json))
      )
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2022-08-14
    • 2021-09-26
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多