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

IT技术 reactjs redux axios redux-form
2021-04-16 01:48:54

我是 React JS 和 Redux 的新手,入门太难了。我正在尝试使用 Axios 发出 POST 请求,但我无法做到。可能是我在容器文件中遗漏了一些东西。下面是代码。检查plnkr

更新: 提交后我收到@@redux-form/SET_SUBMIT_SUCCEEDED 消息。但是当我检查网络选项卡时,我没有看到对 API 的调用。而且当我安慰提交的值时,我只看到 name 和 fullname 值。它不包含徽标和详细信息。我错过了什么?

组件文件

   import React, { PureComponent } from 'react'
   import PropTypes from 'prop-types'
   import { Field,reduxForm } from 'redux-form'
   import {   Columns,Column, TextArea, Label,Button  } from 'bloomer'
   import FormField from 'FormField'

   const validate = (values) => {
     const errors = {}
    const requiredFields = 
      ['organizationName','organizationFullName','organizationDetails']

    requiredFields.forEach((field) => {
     if (!values[field]) {
     errors[field] = 'This field can\'t be empty!'
    }
  })
     return errors
}

  const formConfig = {
   validate,
   form: 'createOrganization',
   enableReinitialize: true
   }

  export class CreateOrganization extends PureComponent {
   static propTypes = {
     isLoading:PropTypes.bool.isRequired,
     handleSubmit: PropTypes.func.isRequired, // from react-redux     
     submitting: PropTypes.bool.isRequired // from react-redux
    }
   onSubmit = data => {
     console.log(data)
   }
  render () {
     const { handleSubmit,submitting,isLoading } = this.props
      return (
        <Columns isCentered>
        <form onSubmit={handleSubmit(this.onSubmit.bind(this))} > 

          <Column isSize='3/6' >        
            <Label>Organization Name</Label>             
            <Field 
              name="organizationName"
              component={FormField}
              type="text"
              placeholder="Organization Name"
            />   
          </Column>       


          <Column isSize='3/6'>
            <Label>Organization Full Name</Label>              
            <Field
              name="organizationFullName"
              component={FormField}
              type="text"
              placeholder="Organization Full Name"
            />  
          </Column> 


           <Column isSize='3/6'>            
            <Label>Organization Logo</Label>              
            <Input                  
              name="organizationLogo"                  
              type="file"
              placeholder="Logo"
            /> 
          </Column>

          <Column isSize='3/6'>
            <Label>Organization Details</Label>         
                <TextArea placeholder={'Enter Details'} />               
          </Column>          


          <Column >
            <span className="create-button">
              <Button type="submit" isLoading={submitting || isLoading} isColor='primary'>
                Submit
              </Button>  
            </span> 
              <Button type="button" isColor='danger'>
                Cancel
              </Button>                
          </Column>  

        </form>
      </Columns>
    )    
  }
}

  export default reduxForm(formConfig)(CreateOrganization)

容器文件

   import React, { PureComponent } from 'react'
   import PropTypes from 'prop-types'
   import { connect } from 'react-redux'
   import Loader from 'Loader'
   import organization from 'state/organization'
   import CreateOrganization from '../components/createOrganization'

   export class Create extends PureComponent {
   static propTypes = {    
     error: PropTypes.object,
     isLoaded: PropTypes.bool.isRequired,  
     create: PropTypes.func.isRequired,   
    }
    onSubmit = data => {
      this.props.create(data)
    }

    render () {
      const { isLoaded, error } = this.props
    return (      
       <CreateOrganization onSubmitForm={this.onSubmit} isLoading=
         {isLoading} />    
     )
   }
 }

   const mapStateToProps = state => ({
     error: organization.selectors.getError(state),
     isLoading: organization.selectors.isLoading(state)
   })

    const mapDispatchToProps = {
      create: organization.actions.create
    }


  export default connect(mapStateToProps, mapDispatchToProps)(Create)
4个回答

您的 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
})

代码沙盒

看来您的配置不允许 redux-thunk 提交触发您的 api 请求的操作。检查您的applyMiddleware( your_middleware?, thunk, logger)(createStore) 然后尝试在不使用的情况下实现逻辑redux-form
2021-05-23 01:48:54
检查此答案,如果您遇到任何困难,请告诉我
2021-05-28 01:48:54
我仍然在控制台中收到“@@redux-form/SET_SUBMIT_FAILED”
2021-05-31 01:48:54
会看看。谢谢
2021-06-18 01:48:54
我添加了一个包含所有错误纠正的 codeSandbox,您需要使用 combineReducers 并在其中设置 redux-form。除此之外还有其他错误,例如未对组件使用大写字符。如果您仍然遇到麻烦,请告诉我
2021-06-20 01:48:54

在 redux-saga 的帮助下,您可以轻松做到这一点。

关于 redux-saga:

redux-saga 是一个旨在使应用程序副作用(即异步事物,如数据获取和不纯事物,如访问浏览器缓存)更易于管理、更有效地执行、更易于测试和更好地处理故障的库。

安装:

$ npm install --save redux-saga 

或者

$ yarn 添加 redux-saga

请参考链接:https : //github.com/redux-saga/redux-saga

Redux 动作创建者显然不支持异步动作,而这正是您试图对 post 请求执行的操作。Redux Thunk 应该对此有所帮助。

你需要一个看起来像这样的 store.js 文件:

//npm install --save redux-thunk

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducer.js';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk) //needed so you can do async
);

这是您的操作文件的外观。Create 成为一个动作创建者,它返回一个函数,然后执行发布请求,并允许您在那里进行分派,从而允许您更新您的商店/状态。

import axios from 'axios'
import { CREATE_ORGANIZATION, CREATE_ORGANIZATION_SUCCESS, CREATE_ORGANIZATION_FAILURE,

       } from './constants'
import * as selectors from './selectors'

/*
  CREATE ORGANIZATION
*/
//uses redux-thunk to make the post call happen
export function create (values) {
  return function(dispatch) {
    return axios.post('/url', values).then((response) => {
      dispatch({ type: 'Insert-constant-here'})
      console.log(response);
    })
    }
  }

此外,您需要像这样将您创建的 onSubmit 方法传递到 onSubmitForm 中。我不确定 isLoading 是从哪里来的,因为我没有看到它被导入到那个容器组件中,所以你可能也想看看它。:

  <createOrganization onSubmitForm={this.onSubmit.bind(this)} isLoading={isLoading} />
是的,在那里输入动作类型。
2021-05-28 01:48:54
'Insert-constant-here' 是一种类似于 CREATE_ORGANIZATION_SUCCESS 的动作类型吗?
2021-05-30 01:48:54
我仍然在控制台中收到“@@redux-form/SET_SUBMIT_FAILED”
2021-05-30 01:48:54
我更新了我的答案。我想你会想要在那里做一些改变
2021-06-05 01:48:54
仍然没有调用 API
2021-06-08 01:48:54

我建议使用redux-promise-middleware这个库要求动作有一个命名属性payload这是一个Promise,这是很容易使用axios然后,它集成了Redux到后缀根动作类型(例如GET_CUSTOMERS)与PENDINGFULFILLED,和REJECTED和火灾的行动。

触发动作与任何其他动作相同。

店铺

import {applyMiddleware, compose, createStore} from 'redux';
import promiseMiddleware from 'redux-promise-middleware';
import reducer from './reducers';

let middleware = applyMiddleware(promiseMiddleware());
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const enhancer = composeEnhancers(middleware);

export default createStore(reducer, enhancer);

行动

export function getCustomers() {
  return {
    type: 'GET_CUSTOMERS',
    payload: axios.get('url/to/api')
      .then(res => {
        if (!res.ok) throw new Error('An error occurred.');
        return res;
      })
      .then(res => res.json())
      .catch(err => console.warn(err));
  };
}

减速器

export default function(state = initialState, action) => {
  switch (action.type) {
    case 'GET_CUSTOMERS_PENDING':
      // this means the call is pending in the browser and has not
      // yet returned a response
      ...
    case 'GET_CUSTOMERS_FULFILLED':
      // this means the call is successful and the response has been set
      // to action.payload
      ...
    case 'GET_CUSTOMERS_REJECTED':
      // this means the response was unsuccessful so you can handle that
      // error here
      ...
    default:
      return state;
  }
}