首页 > 解决方案 > React 在异步调用中调度方法

问题描述

如何在 react 异步调用中调度 redux 函数。当我调用 dispatch functiondispatch(updatingcontact()时,我收到了 dispatch is not defined 的错误。

const UpdateContact = async (URL, method, type, address) => {
dispatch(updatingcontact()
const APIResponse = await fetch(URL, {
    method: POST,
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
    body: JSON.stringify({
        "webContacts": {
            "address": address
        }
    })
})
    .then(response => {
        if (!response.ok) {
            return Promise.reject(response.statusText);
        }
        return response.json();
    })
    .then(status => {
        return status
    })
    .catch(error => {
        console.log(error);
    });
}

我只想调用updatingcontact()里面的函数UpdateContact并调用reducer在UI中显示更新消息。

function updatingcontact() {
return {
    type: ACTIONTYPES.UPDATING_CONTACT
 }
}

标签: reactjsasynchronousreduxmiddleware

解决方案


您需要使用一些异步中间件,例如redux-thunk进行异步 API 调用。使用 redux 的高阶函数connect会将你的 React 组件连接到 redux 存储。

你的 thunk 看起来像这样:

请注意,Redux 会将dispatch参数传递给 thunk 函数以调度操作。

export const updatingContact = (url, address) => {
  return async (dispatch) => { 
    dispatch({ type: ACTIONTYPES.UPDATING_CONTACT_STARTS }) // for showing spinner or loading state in your component

    try {
      const response = axios.post(url, {
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        },

        body: JSON.stringify({
          webContacts: {
            address: address
          }
        })
      })

      dispatch({
        type: ACTIONTYPES.UPDATING_CONTACT_SUCCESS,
        data: { updatedContactList: response.data.updatedContactList }
      })
    } catch (error) {
      dispatch({
        type: ACTIONTYPES.UPDATING_CONTACT_ERROR,
        data: { error: error }
      })
    }
  }
}

之后,无论您的组件需要什么,都可以在 redux 商店中使用。要从dispatch您的UpdateContact组件中,您只需要这样做:

import { updatingContact } from "./actions.js" 

class UpdateContact extends Component {

  componentDidMount() {
      this.props.dispatch(updatingContact()) 
  }

  render() { 
    const {address, phoneNumber } = this.props
    return (
      <div>
        Adress: {address}
        Phone No.: {phoneNumber}
      </div>
    )
  }


const mapStateToProps = () => {
  // return whatever you need from the store like contact details, address, etc
  address: state.updatingContactReducer.address,
  phoneNumber: state.updatingContactReducer.phoneNumber
}

export default connect(mapStateToProps)(UpdateContact)

请注意,如果您不提供mapDispatchToPropsto connect,您仍然可以dispatch在您的组件中使用,因为它在默认情况下是可用的。

如果您提供mapDispatchToProps,那么您现在从组件调度的方式将是 - this.props.updatingContact()

mapDispatchToProps只需将动作创建者与 dispatch 绑定,并将这些新的绑定函数作为 props 传递给组件。


推荐阅读