繁体   English   中英

如何在异步调度完成后执行组件中的方法(thunk 或 action creator)?

[英]How to execute a method in component after a async dispatch completes(thunk or action creator)?

我正在使用 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)));
    };
}

我的要求是在 componentDidMount 方法中我应该能够这样做

componentDidMount() {
   this.props.fetchData('https://.....').then(res => {
       this.notify();
       /// or do something else;
   })
}

任何人都可以提供帮助,或者您需要任何其他输入或工作沙箱..请回复。

您的 thunk 函数itemsFetchData返回函数,没关系。

但是那个返回的函数不返回任何东西,你没有传播你的return response; . 您应该返回axios.get(url)返回的承诺:

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更好的方式than对派遣行动的创建者的功能,你应该设置的东西在你的终极版(如dataLoadedSuccessfullytrue在行动的创建者减速处理itemsFetchDataSuccess ),并检查在它的改变componentDidUpdate ,如:

componentDidUpdate(prevProps) {
   if (this.props.dataLoadedSuccessfully && this.props.dataLoadedSuccessfully !== prevProps.dataLoadedSuccessfully) {
       this.notify();       
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM