栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用React,Redux和Axios处理异步请求?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用React,Redux和Axios处理异步请求?

您的redux操作创建者必须是普通的,反对的,并应使用强制性的key进行调度和操作

type
。但是,使用像
redux-thunk
您这样的自定义中间件可以
axios
在操作创建者内调用请求,因为没有定制,
middlewares
操作创建者就需要返回普通对象

您的动作创建者看起来像

export function create (values) {  return (dispatch) => {     dispatch({type: CREATE_ORGANIZATION});     axios.post('/url', values).then((res) =>{ dispatch({type: CREATE_ORGANIZATION_SUCCESS, payload: res});        })        .catch((error)=> { dispatch({type: CREATE_ORGANIZATION_FAILURE, payload: error});        })  }}

你的减速器看起来像

export default (state = initialState, action) => {  const payload = action.payload   switch (action.type) {        case CREATE:      return {        ...state,        loading: true,        loaded: false      }    case CREATE_SUCCESS:      return {        ...state,        data: state.data.concat(payload.data),        loading: false,        loaded: true,        error: null      }      }    case CREATE_FAILURE:      return {        ...state,        loading: false,        loaded: true,        error: payload      }    default:      return state  }}

现在,在创建商店时,您可以像

import thunk from 'redux-thunk';import { createStore, applyMiddleware } from 'redux';const store = createStore(  reducer,  applyMiddleware(thunk));

除此之外,您还需要设置redux表单

您需要使用CombineReducers和Provider来传递商店

import reducer from './reducer';import { combineReducers } from 'redux';import { reducer as formReducer } from 'redux-form'export const rootReducer = combineReducers({   reducer,   form: formReducer})

CodeSandbox



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/394657.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号