Redux-如何调用动作并等待其解决

时间:2019-01-05 18:19:10

标签: reactjs react-native redux react-thunk

我正在使用react native + redux + redux-thunk 我对redux没有太多经验,对本机也没有反应

我正在组件内部调用一个动作。

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 个答案:

答案 0 :(得分:2)

您可以从操作中返回一个承诺,以便调用变为 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来处理您的诺言:

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

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

这做同样的事情。

答案 1 :(得分:1)

我不明白问题所在,但是也许可以帮忙

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){
  ...
 }

答案 2 :(得分:0)

如果仍有困惑,我已经编写了完整的代码。 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));