React redux创建一个动作来获取应用程序其他部分的状态

时间:2018-10-11 20:38:35

标签: reactjs redux redux-thunk

我有一个react / redux应用程序,并使用redux-thunk。

我在应用程序的一部分中有一个按钮,当单击该按钮时,它会触发一个动作,该动作采取应用程序某些完全不同的部分的状态并将其发送到后端。后端响应到达时,应修改某些应用程序状态。我该怎么办?

检查以下示例:


带有按钮的应用程序的一部分:

// MyModalContainer.js
import {connect} from 'react-redux';
import {MyModal} from './MyModal';

const mapStateToProps = (state) => ({
});
const mapDispatchToProps = (dispatch) => ({
    orderButtonHandler: () => {...to do...}
});

const MyModalContainer = connect(mapStateToProps, mapDispatchToProps)(MyModal);
export {MyModalContainer};


///////////////////////////////////
// MyModal.js
import React from 'react';
import Button from '@material-ui/core/Button';
class MyModal extends React.Component {
    render() {
        return (
            <div>
                <Something>....</Something>
                <Something2>....</Something2>
                <Button onClick={this.props.orderButtonHandler} color="primary">
                    Order
                </Button>
            </div>
        );
    }
}
export {MyModal};

在单击按钮时要发送到后端的数据存储在redux下:

state.cartData = {
     data1: ....,
     data2: ....,
     data3: ....
}

,并且未在MyModal中呈现


一个选择是,我可以通过state.cartDataMyModal发送到MyModalContainer,然后该按钮会将其发送到orderButtonHandler。但是随后MyModal会随时重绘state.cartData,即使它没有从state.cartData绘制任何内容。

1 个答案:

答案 0 :(得分:0)

我找到了令我满意的解决方案,但是如果您有更好的解决方案,请在此答案下方发布或发表评论。

// MyModalContainer.js
import {connect} from 'react-redux';
import {MyModal} from './MyModal';
import { makeOrder } from './modules/cart';

const mapStateToProps = (state) => ({
});
const mapDispatchToProps = (dispatch) => ({
    orderButtonHandler: () => {dispatch(makeOrder());}
});

const MyModalContainer = connect(mapStateToProps, mapDispatchToProps)(MyModal);
export {MyModalContainer};

makeOrder函数利用带有 getState 的redux-thunk:

// modules/cart.js
const makeOrders = () => async (dispatch, getState) => {

    const stateOfSomeOtherPartOfApp = getState().cart; 
    // THE CRITICAL PART IS TO GET THE STATE IN THE ASYNC ACTION CREATOR 
    // AS I FOUND OUT THAT getState IS PROVIDED BY REDUX THUNK

    const orderResponse = await makeAsyncPost(stateOfSomeOtherPartOfApp);
    dispatch({type: 'orderResponseReceived', data: orderResponse});
};