在Reactjs中运行Ajax调用函数的最佳位置在哪里?

时间:2016-10-17 17:05:34

标签: ajax reactjs redux

我正在使用Redux处理Reactjs网络应用程序。

所以现在我在我的组件中运行Ajax调用。

componentDidMount(){
    const props = this.props;
    const deafaultUrl = apiUrl['development'];

    $.ajax({
        url: deafaultUrl + '/v1/movies/top_rated_homepage',
        dataType: 'json',
        contentType: 'application/json',
        success: function(data) {
            return props.update_homepage_best_movie_data(data);
        },
        error: function(xhr, status, err) {
            console.error(status, err.toString());
            return {}
        }
    });
}

现在一切正常。 但在我阅读了redux文档之后,他们建议在action.js文件中发送请求。

import fetch from 'isomorphic-fetch'

export const REQUEST_POSTS = 'REQUEST_POSTS'
function requestPosts(subreddit) {
  return {
    type: REQUEST_POSTS,
    subreddit
  }
}

export const RECEIVE_POSTS = 'RECEIVE_POSTS'
function receivePosts(subreddit, json) {
  return {
    type: RECEIVE_POSTS,
    subreddit,
    posts: json.data.children.map(child => child.data),
    receivedAt: Date.now()
  }
}

export function fetchPosts(subreddit) {

  return function (dispatch) {

    dispatch(requestPosts(subreddit))

    return fetch(`http://www.reddit.com/r/${subreddit}.json`)
      .then(response => response.json())
      .then(json =>

        dispatch(receivePosts(subreddit, json))
      )

  }
}

这两种方法之间的优缺点是什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

推荐使用第二

Redux基于Flux架构构建。这遵循以下模式 Flux

Web API是您需要放置所有API调用的地方。这样做的原因是,当您将每个API导出为一个操作时,它可以在n个组件中使用。

例如,如果在组件<App/>中放置一个AJAX调用,并且如果要在其他组件<Menu/>中使用相同的AJAX调用,则使用早期方法是不可能的。但是,当您将每个AJAX调用导出为操作时,这些操作将在所有组件中可用,并且可以使用。

优点:

  1. 提高可重用性
  2. 从视图中提取API。
  3. 更好的代码维护
  4. 易于调试。
  5. 缺点:

    1. 扰乱FLUX模式
    2. 降低可重用性
    3. 冗余代码
    4. 很难扩展。
    5. 希望这会有所帮助。

相关问题