如何在单个 React 组件中正确调度相同的操作两次



我正在尝试了解我在 react 应用程序中使用 redux 面临的数据获取挑战的最佳方法。

简而言之,我需要两次调度相同的提取(在本例中为fetchPlayerSeasonStats),并保存两个数据提取。第一次获取获取单个玩家的统计信息(通过获取可选的第一个参数thisPlayerId),第二次获取省略参数并获取更大的数据集。

我在下面尝试做的如下:

(a) 首次获取playerSeasonStats

(b) 在componentDidUpdate()中,检查第一次获取是否完成(if条件检查数组序列)。

(c) 如果满足条件,则使用状态变量thisPlayersSeasonStats来存储数据的原始提取。

(d) 然后,使用另一个调度操作重新获取较大的数据集。

。除了我收到的警告说"不要更新组件 DidMount 中的状态"之外,一般来说,我不确定这种方法是否正确,或者它是否是一种"反模式"/糟糕的 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-thunk 是如何工作的。

Redux Thunk 中间件允许您编写返回函数而不是操作的动作创建者

我认为这就是fetchPlayerSeasonStats本质上要做的事情。它返回一些获取玩家的异步函数。Redux-thunk帮助调度它(我想你使用Redux-thunk。如果您使用其他异步中间件,它应该基本相同)。

因此,我们可以编写将返回函数(如fetchPlayerSeasonStats)的动作创建器,但内部不会调度动作,而是另一个函数。因此,我们将具有函数调度功能,它将调度操作:-)

例如

fetchAllPlayerStats (thisPlayerId, appSeasonValue) => dispatch => {
dispatch(fetchPlayerSeasonStats(thisPlayerId, appSeasonValue));
dispatch(fetchPlayerSeasonStats(null, appSeasonValue));
}

然后,您可以使用componentWillMount中的this.props.dispatch(fetchAllPlayerStats(thisPlayerId, this.props.appSeason.value))一次获取所有数据。

提示。fetchAllPlayerStats的当前实现将一次获取所有数据。如果您添加 async/await 关键字,您将首先获得单个玩家的数据,然后获得更大的数据集。修改后的版本将如下所示

fetchAllPlayerStats (thisPlayerId, appSeasonValue) => async dispatch => {
await dispatch(fetchPlayerSeasonStats(thisPlayerId, appSeasonValue));
await dispatch(fetchPlayerSeasonStats(null, appSeasonValue));
}

这是展示逻辑的简单示例

最新更新