reactjs - 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
}
}
解决方案
您需要使用一些异步中间件,例如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)
请注意,如果您不提供mapDispatchToProps
to connect
,您仍然可以dispatch
在您的组件中使用,因为它在默认情况下是可用的。
如果您提供mapDispatchToProps
,那么您现在从组件调度的方式将是 - this.props.updatingContact()
。
mapDispatchToProps
只需将动作创建者与 dispatch 绑定,并将这些新的绑定函数作为 props 传递给组件。
推荐阅读
- python - 未找到 Django Url 模式
- c# - 如何使用 HttpWebRequest 在 Dynamics 365 中发布数据
- wordpress - 如何让 wordpress 为我的 react 应用程序提供服务?
- r - 将 geom_hline 添加到图例
- php - 按计数分组不工作 Mysql Php
- java - 如何使用 Android Java 在 EPSON Receipt Printer 上打印缅甸 Unicode 字体?
- amazon-cognito - 如果禁用自动预热,如何使用 ses 专用 ip?
- python - 如何根据python中的用户输入在函数中逐一传递动态列表值?
- react-native - TypeError:未定义不是对象(评估“VisibleComponent.props”)
- gtk - 在 Gtk 中使用 cairo 时,我只能在不透明部分开始移动拖动吗?