首页 > 解决方案 > 我应该在 react-redux 应用程序中哪里计算派生数据?

问题描述

我有一个应用程序,用户可以在其中将元素添加到时间线(简化为列表)。但是这个动作调度了另外几个动作,其中一个是虚拟生成的元素。实际上,元素回答了这个问题:你想要另一个元素吗?

我的问题是我应该在哪里计算这个?例如,我应该在 redux 中更新状态还是在 mapStateToProps 中渲染之前计算它?如果我应该在 mapStateToProps 中执行此操作,请记住其中一项建议被拒绝了。

const TimelineElement = ({type}) => {
    switch (type) {
        case 'Plane':
            return <Plane/>;
        case 'Train':
            return <Train/>;
        case 'Suggestion':
            return <Suggestion/>;
        default:
            return null;

    }

};

const PlaneTravel = () => {
    return <div>Plane</div>
};

const TrainTravel = () => {
    return <div>Train</div>
};

const Suggestion = () => {
    return <div>Accommodation suggestion</div>
};


//actions
const addElement = (element) => (dispatch) => {

    //add element stuff, then:

    dispatch(addSuggestions());
    dispatch(generateReturnElements());
};

const addSuggestions = () => (dispatch) => {
    // only if conditions are met,
    // put between elements some suggestions with question:
    // do you want add accommodation element here?
};

const generateReturnElements = () => (dispatch) => {
    // if someone checks the checkbox that mean round trip,
    // i want to put additional plane or train element to timeline

};


class App extends React.Component {


    render() {
        const elements = this.props.elements.map(element => {
            return <TimelineElement type={element.type}/>
        });

        return (
            <Timeline>
                {elements}
            </Timeline>
        );

    }
}

const mapStateToProps = (state) => ({
    elements: getElements(state)
});

const mapDispatchToProps = (dispatch) => bindActionsCreator({
    addElement,
}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(App);

标签: reactjsreact-redux

解决方案


您可以使用 reselect https://github.com/reduxjs/reselect之类的库来计算派生的状态数据。试试看。它对您的应用程序性能也有帮助。您可以停止浪费的重新渲染。


推荐阅读