How to properly make REST calls from ReactJS + Redux application?

后端 未结 3 1260
南笙
南笙 2020-12-23 14:27

I\'m using ReactJS + Redux, along with Express and Webpack. There is an API built, and I want to be able to make REST calls -- GET, POST, PUT, DELETE -- from the client-side

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 15:05

    This is the primary use case for libraries like redux-thunk, redux-saga, and redux-observable.

    redux-thunk is the simplest, where you would do something like this:

    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()
      }
    }
    
    // Meet our first thunk action creator!
    // Though its insides are different, you would use it just like any other action creator:
    // store.dispatch(fetchPosts('reactjs'))
    
    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(`http://www.reddit.com/r/${subreddit}.json`)
          .then(response => response.json())
          .then(json =>
    
            // We can dispatch many times!
            // Here, we update the app state with the results of the API call.
    
            dispatch(receivePosts(subreddit, json))
          )
    
          // In a real world app, you also want to
          // catch any error in the network call.
      }
    }
    

    The above example is taken directly from http://redux.js.org/docs/advanced/AsyncActions.html which is really the definitive source for answers on your question.

提交回复
热议问题