【问题标题】:React dispatch a method in async callReact 在异步调用中调度方法
【发布时间】:2020-03-20 14:09:28
【问题描述】:

如何在 react 异步调用中调度 redux 函数。当我调用调度函数dispatch(updatingcontact() 时,我收到未定义调度的错误。

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);
    });
}

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

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

【问题讨论】:

  • 你可以使用redux thunk
  • @HMR 我在使用return (dispatch) => {dispatch(updatingcontact())} 时收到此错误Syntax error: await is a reserved word
  • 将此作为异步中间件检查出来HERE

标签: reactjs asynchronous redux middleware


【解决方案1】:

您需要使用一些异步中间件,例如 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 商店中获得。从你的UpdateContact 组件到dispatch,你只需要这样做:

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)

请注意,如果您不向connect 提供mapDispatchToProps,您仍然可以在组件中使用dispatch,因为它默认可用。

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

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

【讨论】:

    【解决方案2】:

    正如 HMR 所述,您应该使用 redux-thunk 在 redux 操作中进行异步调用。

    最简单的方法是查看redux toolkit,它正在为您安装所有标准的 redux 中间件(包括 redux-thunk)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2015-11-28
      相关资源
      最近更新 更多