如何在 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
)来进行异步 API 调用。使用 redux 的高阶函数 connect
将你的 React 组件连接到 redux 存储。
你的thunk看起来像这样:
请注意,Redux 会将 dispatch
参数传递给 thunk 函数以分派(dispatch)操作。
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)
请注意,如果您不向 connect
提供 mapDispatchToProps
,您仍然可以在组件中使用 dispatch
因为它默认可用。
如果您提供 mapDispatchToProps
,那么您现在从组件分派(dispatch)的方式将是 - this.props.updatingContact()
。
mapDispatchToProps
只是将 Action 创建者与调度绑定(bind)在一起,并将这些新的绑定(bind)函数作为 props 传递给组件。
关于reactjs - React 在异步调用中调度一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60775805/