我正在编写一些通用的 Todo-List 组件,具有以下功能
- 分页/排序
- 在 URL 中保留一部分状态(页面、排序)
- 使用 HTTP 请求异步获取数据(使用 redux-saga)
现在,我正在尝试为 redux 操作的“最佳”序列找到一种模式,以使其正常工作。
我想要以下行为:
当 Todo 组件加载时:读取 URL 查询参数并使用它来获取数据。
当用户单击
sort by name
(或next page
或filer by xyz
)URL 中的查询参数应更新并应获取下一个数据。
我当前的代码做什么:
我正在创建 props todos
,pagination
并sort
在 react-redux 中mapStateToProps
:
state => {
todos: state.venues.page,
pagination: parsePagination(state.router.location.search),
sorting: parseSorting(state.router.location.search)
}
在组件中,我有生命周期和方法,例如:
componentDidMount() {
// these props come from redux's "mapStateToProps"
dipatch(executeFetch(this.props.pagination, this.props.sorting));
}
onSortingChange = (sorting) => {
// this will use connected-react-router's "push"
// to update the browser's URL
dispatch(dispatchSetSortingQueryParam(sorting));
}
onPaginationChange = (pagination) => {
// same as "onSortingChange"
dispatch(setPaginationQueryParam(sorting));
}
现在是大问号:
在哪里/我应该如何运行executeFetch
时,sorting
或pagination
改变?
组件DidUpdate ?这看起来很有希望,但是:它创建了一个无限循环,因为每个
executeFetch
都会触发一个组件更新,然后会componentDidUpdate
一次又一次地运行。我可以在这里检查pagination
和/或sorting
是否已更改,然后运行executeFetch
,但是每次任何props更改时,我都会为这两个props获取一个新对象实例,这需要进行深度相等性检查。不太好。executeFetch
在每个onSortingChange
和的末尾添加onPaginationChange
。这似乎有效,但感觉有点多余。另一个问题是,我无法使用this.props.sorting
和this.props.pagination
运行executeFetch
,因为这些props尚未更新。
你如何在你的应用程序中解决这个问题?