React如何在异步调用中分发方法

7
如何在React异步调用中分发Redux函数。当我调用dispatch函数dispatch(updatingcontact())时,我收到了dispatch未定义的错误。
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 在用户界面上显示更新消息。
function updatingcontact() {
return {
    type: ACTIONTYPES.UPDATING_CONTACT
 }
}

1
你可以使用 redux thunk - HMR
@HMR 我在使用 return (dispatch) => {dispatch(updatingcontact())} 时遇到了 Syntax error: await is a reserved word 错误。 - Maria Jeysingh Anbu
请查看此异步中间件链接 - Ibrahim shamma
2个回答

4

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

您的 thunk 函数应该长这个样子:

const fetchData = () => {
  return (dispatch) => {
    // 在这里进行异步 API 调用
  }
}

请注意,Redux 会将 dispatch 参数传递给 thunk 函数,以便进行 action 派发。

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组件进行调度,只需执行以下操作:

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)
注意,如果您不提供mapDispatchToPropsconnect,则仍然可以在组件中使用dispatch,因为它默认可用。

如果您提供了mapDispatchToProps,现在从组件中分派的方式将是- this.props.updatingContact()

mapDispatchToProps只是将操作创建器与分派绑定,并将这些新的绑定函数作为属性传递给组件。


2
如HMR所提到的,您应该使用redux-thunk在redux actions中进行异步调用。
最简单的方法是查看redux toolkit,它会为您安装所有标准的redux中间件(包括redux-thunk)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接