reactjs - 我应该在 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);
解决方案
您可以使用 reselect https://github.com/reduxjs/reselect之类的库来计算派生的状态数据。试试看。它对您的应用程序性能也有帮助。您可以停止浪费的重新渲染。
推荐阅读
- c# - FCM(FirebaseMessagingService)OnNewToken 没有被 Android 击中
- python - 如何使用 python 从网站中提取表
- javascript - 为 fetch api 处理不同的变量
- android - 同时录制前后摄像头
- php - 我需要知道用于查询嵌套关系并返回结果的 Laravel Eloquent 语法
- java - Spring CLI 未找到“测试”命令
- ios - 如何快速设置 CAShapeLayer 的 strokeColor
- wordpress - 找不到对象!WordPress
- python - 导入包并运行玩具示例测试
- python - AttributeError:“int”对象没有属性“ndim”