开发者社区> 问答> 正文

#React 如何在Redux中提出AJAX请求?

#React 如何在Redux中提出AJAX请求?

展开
收起
因为相信,所以看见。 2020-05-07 22:40:14 460 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    您可以使用redux-thunk允许您定义异步操作的中间件。

    让我们举一个使用fetch API将特定帐户作为AJAX调用获取的示例:

    export function fetchAccount(id) {
      return dispatch => {
        dispatch(setLoadingAccountState()) // Show a loading spinner
        fetch(`/account/${id}`, (response) => {
          dispatch(doneFetchingAccount()) // Hide loading spinner
          if (response.status === 200) {
            dispatch(setAccount(response.json)) // Use a normal function to set the received state
          } else {
            dispatch(someError)
          }
        })
      }
    }
    
    function setAccount(data) {
     return { type: 'SET_Account', data: data }
    }
    
    2020-05-07 22:40:39
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
利用编译将 Vue 组件转成 React 组件 立即下载
React Native 全量化实践 立即下载
React在大型后台管理项目中的工程实践 立即下载