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

Job*_*dev 3 reactjs react-native redux react-thunk

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

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

this.props.checkClient(cliente);

if(this.props.clienteIsValid){
   ...
}
Run Code Online (Sandbox Code Playgroud)

在该操作中,将调用一个需要花费几秒钟的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) => {  });

    }
}
Run Code Online (Sandbox Code Playgroud)

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

mic*_*nil 6

您可以从操作中返回一个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);
Run Code Online (Sandbox Code Playgroud)

这可能超出了问题的范围,但是如果您愿意,可以使用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) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这做同样的事情。