代码之家  ›  专栏  ›  技术社区  ›  Jobsdev

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

  •  1
  • Jobsdev  · 技术社区  · 6 年前

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

    2 回复  |  直到 4 年前
        1
  •  9
  •   micnil    6 年前

    您可以从操作中返回一个承诺,以便调用成为 :

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

    这也是同样的道理。

        2
  •  1
  •   Yasin Tazeoglu    6 年前

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

    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){
      ...
     }
    
        3
  •  0
  •   bikram    4 年前

    如果仍然有混淆,我已经写了完整的代码。这个 许诺

    行动

    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));
    
    推荐文章