【发布时间】:2018-08-10 03:00:03
【问题描述】:
我正在编写一些通用的 Todo-List 组件,具有以下功能
- 分页/排序
- 在 URL 中保留部分状态(页面、排序)
- 使用 HTTP 请求异步获取数据(使用 redux-saga)
现在我正在尝试为“最佳”redux 操作序列找到一种模式,以使其正常工作。
我想要以下行为:
当 Todo 组件加载时:读取 URL 查询参数并使用它来获取数据。
当用户点击
sort by name(或next page或filer by xyz)时,应更新URL中的查询参数并获取下一个数据。
我当前的代码做了什么:
我正在 react-redux 的 mapStateToProps 中创建道具 todos、pagination 和 sort:
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));
}
现在是个大问号:
当sorting 或pagination 发生变化时,我应该在哪里/如何运行executeFetch?
componentDidUpdate ? 这看起来很有希望,但是:它创建了一个无限循环,因为每个
executeFetch都会触发一个组件更新,然后会一次又一次地运行componentDidUpdate。我可以在这里检查pagination和/或sorting是否已更改,然后运行executeFetch,但是每次任何道具更改时,我都会为这两个道具获得一个新的对象实例,这需要然后进行深度相等检查。不好。在每个
onSortingChange和onPaginationChange的末尾添加executeFetch。这似乎有效,但感觉有点多余。另一个问题是,我不能使用this.props.sorting和this.props.pagination来运行executeFetch,因为这些道具还没有更新。
您如何在应用程序中解决这个问题?
【问题讨论】:
-
我想我有一个很好的答案。你有什么东西来了吗?
标签: reactjs redux pagination redux-saga query-parameters