【发布时间】:2019-06-14 08:00:57
【问题描述】:
我正在尝试了解在我的 react 应用程序中使用 redux 所面临的数据获取挑战的最佳方法。
简而言之,我需要分派相同的提取(在本例中为fetchPlayerSeasonStats)两次,并保存两次提取的数据。第一次获取获取单个玩家的统计信息(通过获取可选的第一个参数thisPlayerId),第二次获取省略参数并获取更大的数据集。
我在下面尝试做的事情如下:
(a) 第一次获取playerSeasonStats
(b) 在componentDidUpdate() 中,检查第一次提取是否已完成(if 条件检查数组长度)。
(c) 如果条件满足,则使用状态变量thisPlayersSeasonStats 来存储原始获取的数据。
(d) 然后,使用另一个调度的操作重新获取更大的数据集。
...除了我收到的警告说“不要更新 componentDidMount 中的状态”,一般来说,我不确定这种方法是否正确或者它是否是“反模式”/错误的 React/ Redux 编码风格。我想确保我这样做是正确的,因此对以下代码(特别是 componentDidUpdate() 函数)的任何审查将不胜感激!
谢谢!
// Import React Components
import React, { Component } from 'react';
import { connect } from 'react-redux';
// Import Fetches
import { fetchPlayerSeasonStats } from '../../../actions/...';
// Create The Component
class MyComponentHere extends Component {
constructor(props) {
super(props);
this.state = {
thisPlayerSeasonStats: []
};
}
componentDidMount() {
let thisPlayerId = this.props.playerInfo._id;
this.props.dispatch(fetchPlayerSeasonStats(thisPlayerId, this.props.appSeason.value));
}
componentDidUpdate(prevProps) {
console.log('prevProps: ', prevProps);
if (this.props.appSeason !== prevProps.appSeason) { this.refetchTeamsStats(); }
if (prevProps.playerSeasonStats.length === 0 && this.props.playerSeasonStats.length === 1) {
this.setState({ thisPlayerSeasonStats: this.props.playerSeasonStats });
this.props.dispatch(fetchPlayerSeasonStats(null, this.props.appSeason.value));
}
}
render() {
// Handle Initial Loading Of Data
if (this.state.thisPlayerSeasonStats.length === 0) { return <LoadingSpinner />; }
// The Return
return (
<div> Return Dont Matter For here </div>
);
}
}
function mapStateToProps(reduxState) {
return {
playerSeasonStats: reduxState.playerSeasonStatsReducer.sportsData,
loading: (reduxState.playerSeasonStatsReducer.loading),
error1: reduxState.playerSeasonStatsReducer.error
};
}
export default connect(mapStateToProps)(MyComponentHere);
【问题讨论】:
-
如果你已经在你的应用程序中使用 redux,应该看看 redux-thunk 或 redux-saga,对于小范围
redux-thunk对你来说已经足够了,尝试调用请求并处理thunk中的所有逻辑然后只是dispatch一次到reducer与完整数据。 -
不要读它。这是随机的。我认为您应该考虑以不同的方式对其进行架构,尽管您需要两次提取,但它似乎属于同一操作。您应该创建一个元操作,将这两个调度合并为一个,然后视图只需在挂载时触发一个操作