Redux - 如何调用一个动作并等待它被解决

IT技术 reactjs react-native redux redux-thunk
2021-04-09 14:22:11

我正在使用 react native + redux + redux-thunk 我对 redux 和 react native 没有太多经验

我正在我的组件中调用一个动作。

this.props.checkClient(cliente);

if(this.props.clienteIsValid){
   ...
}

在该操作中,调用一个需要几秒钟的 api。

export const checkClient = (cliente) => {
    return dispatch => {

        axios.get(`${API_HOST}/api/checkclient`, header).then(response => {

            dispatch({type: CHECK_CLIENT, payload: response.data }); //valid or invalid

        }).catch((error) => {  });

    }
}

我的问题是如何延迟操作的返回,直到 api 响应完成?我需要 api 响应才能知道客户端是有效还是无效。也就是说,我需要解析动作,然后验证客户端是有效还是无效。

3个回答

您可以从操作中返回一个Promise,以便调用变为thenable

// Action
export const checkClient = (cliente) => {
    return dispatch => {
        // Return the promise
        return axios.get(...).then(res => {
            ...
            // Return something
            return true;
        }).catch((error) => {  });
    }
}


class MyComponent extends React.Component {

    // Example
    componentDidMount() {
        this.props.checkClient(cliente)
            .then(result => {
                // The checkClient call is now done!
                console.log(`success: ${result}`);

                // Do something
            })
    }
}

// Connect and bind the action creators
export default connect(null, { checkClient })(MyComponent);

这可能超出了问题的范围,但如果您愿意,可以使用 async await 而不是then处理您的Promise:

async componentDidMount() {
    try {
        const result = await this.props.checkClient(cliente);
        // The checkClient call is now done!
        console.log(`success: ${result}`)

        // Do something
    } catch (err) {
        ...
    }
}

这做同样的事情。

我在结果中变得不确定。为什么未定义@micnil
2021-05-30 14:22:11
@micnil 你能告诉我如何使用 React 钩子 useDispatch() 函数来完成这项工作吗?
2021-06-16 14:22:11

我不明白这个问题,但也许这会有所帮助

export const checkClient = (cliente) => {
  return dispatch => {
    dispatch({type: CHECK_CLIENT_PENDING });

    axios.get(`${API_HOST}/api/checkclient`, header).then(response => {

        dispatch({type: CHECK_CLIENT, payload: response.data }); //valid or invalid

    }).catch((error) => {  });

   }
}

...


 this.props.checkClient(cliente);

 if(this.props.clienteIsPending){
  ...
 }

 if(this.props.clienteIsValid){
  ...
 }

如果仍有困惑,我已经编写了完整的代码。Promise应适用于异步Redux的行动调用序列

行动

export const buyBread = (args) => {
  return dispatch => {
    return new Promise((resolve, reject) => {

        dispatch({type: BUY_BREAD_LOADING });
        // or any other dispatch event

        // your long running function
       
        dispatch({type: BUY_BREAD_SUCCESS, data: 'I bought the bread'});
        // or any other dispatch event

        // finish the promise event
        resolve();

        // or reject it
        reject();
    
    });
}

export const eatBread = (args) => {
  return dispatch => {
    return new Promise((resolve, reject) => {

        dispatch({type: EAT_BREAD_LOADING });
        // or any other dispatch event

        // your long running function
       
        dispatch({type: EAT_BREAD_SUCCESS, data: 'I ate the bread'});
        // or any other dispatch event

        // finish the promise event
        resolve();

        // or reject it
        reject();
    
    });
}

减速器

const initialState = {}
export const actionReducer = (state = initialState, payload) => {
    switch (payload.type) {
        case BUY_BREAD_LOADING:
           return { loading: true };
        case BUY_BREAD_SUCCESS:
           return { loading: false, data: payload.data };
        case EAT_BREAD_LOADING:
           return { loading: true };
        case EAT_BREAD_SUCCESS:
           return { loading: false, data: payload.data };
}

组件类

import React, {Component} from 'react';

class MyComponent extends Component {
    render() {
        return (
            <div>
                <button onClick={()=>{
                    this.props.buyBread().then(result => 
                        this.props.eatBread();
                        // to get some value in result pass argument in resolve() function
                    );
                }}>I am hungry. Feed me</button>
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    actionReducer: state.actionReducer,
});

const actionCreators = {
    buyBread: buyBread,
    eatBread: eatBread
};

export default connect(mapStateToProps, actionCreators)(MyComponent));