如何在异步调度完成后(thunk或动作创建者)执行组件中的方法?

问题描述 投票:0回答:1

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

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

javascript reactjs redux async-await redux-thunk
1个回答
0
投票

您的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函数更好的方法,应该在redux中进行设置(例如,在动作创建者itemsFetchDataSuccess的化简处理程序中),并在componentDidUpdate`中检查其更改,例如:] >

componentDidUpdate(prevProps) {
   if (this.props.dataLoadedSuccessfully && this.props.dataLoadedSuccessfully !== prevProps.dataLoadedSuccessfully) {
       this.notify();       
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.