我使用 redux 和 redux-thunk 来执行异步操作。
在我的组件中,我有以下代码
class Counter extends Component {
componentDidMount() {
}
notify() {
////some logic
}
//
// other code
//
render() {
// code
}
}
const mapStateToProps = (state) => {
return {
items: state.items,
hasError: state.itemsHaveError,
isLoading: state.itemsAreLoading
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchData: (url) => dispatch(itemsFetchData(url))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ItemList);
我的方法代码是
function itemsFetchData(url) {
return (dispatch) => {
dispatch(itemsAreLoading(true));
axios.get(url)
.then((response) => {
if (response.status !== 200) {
throw Error(response.statusText);
}
dispatch(itemsAreLoading(false));
return response;
})
.then((response) => dispatch(itemsFetchDataSuccess(response.data)))
.catch(() => dispatch(itemsHaveError(true)));
};
}
我的要求是在 componenentDidMount 方法中我应该能够这样做
componentDidMount() {
this.props.fetchData('https://.....').then(res => {
this.notify();
/// or do something else;
})
}
任何人都可以提供帮助吗?或者您需要任何其他输入或工作沙箱。请回复。
最佳答案
你的 thunk 函数 itemsFetchData
返回函数,没问题。
但是返回的函数不会返回任何内容,您没有传播您的返回响应;
。您应该返回 axios.get(url)
返回的 promise :
function itemsFetchData(url) {
return (dispatch) => {
dispatch(itemsAreLoading(true));
// you need to return promise from thunk
return axios.get(url)
.then((response) => {
if (response.status !== 200) {
throw Error(response.statusText);
}
dispatch(itemsAreLoading(false));
return response;
})
.then((response) => dispatch(itemsFetchDataSuccess(response.data)))
.catch(() => dispatch(itemsHaveError(true)));
};
}
<小时/>
IMO 比在分派(dispatch)操作创建器上监听 than
函数更好的方法,您应该在 redux 中设置一些内容(例如,将 dataLoadedSuccessively
设置为 true
操作创建者的reducer处理程序itemsFetchDataSuccess
)并在componentDidUpdate
中检查它的更改,例如:
componentDidUpdate(prevProps) {
if (this.props.dataLoadedSuccessfully && this.props.dataLoadedSuccessfully !== prevProps.dataLoadedSuccessfully) {
this.notify();
}
}
关于javascript - 如何在异步调度完成后执行组件中的方法(thunk 或 Action 创建者)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321143/