reactjs - Redux - 如何调用一个 Action 并等待它被解决

标签 reactjs react-native redux redux-thunk

我正在使用 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 响应来了解客户端是否有效。也就是说,我需要解决该操作,然后验证客户端是否有效。

最佳答案

您可以从操作中返回一个 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 wait 而不是 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) {
        ...
    }
}

这做同样的事情。

关于reactjs - Redux - 如何调用一个 Action 并等待它被解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54054887/

相关文章:

reactjs - 如何在reactjs中使用Jsdoc生成文档?

javascript - 使用自定义 React hook 获取数据

javascript - React Hook "useSelector"在函数中被调用

react-native - React Native Eject 解释

reactjs - 在每次测试之前手动修改initialState并将其传递给商店?

Reactjs BigCalendar 添加事件

React-Native:如何在没有明确宽度和高度的情况下填充全屏?

react-native - React Native - 具有动态高度子项的 FlatList

javascript - 在 angular/ngrx 应用程序中将状态保存到本地存储的逻辑放在哪里

node.js - 在 react 中从数据库获取数据的正确方法是什么?