Fat*_*ani 6 javascript typescript redux
I'm having a hard time implementing Redux in a quiet large website.
I have components connected to the store using the useSelector API I use Reselect to write selectors.
The thing is I don't know where to trigger the bootstrap actions of a page for example.
I have a container made of stateless components, that only takes props and displays them. In the container, one could trigger all the actions to fetch data from an API. (using redux-thunk) The main issue is that the devs should list the actions to be triggered in order to display the page.
But I was wondering if I could just trigger the right action when trying to select data from the store:
export function getComment(state, id) {
const comments = state.comments;
if (comments[id]) {
return comments[id];
}
store.dispatch(CommentActions.getComment(id));
return undefined;
}
Run Code Online (Sandbox Code Playgroud)
The components here just "hook" themselves to data in the store. If the data is already there, it is returned, otherwise the trigger the action that calls the API and returns undefined.
My main interrogation is whether or not this approach is an anti-pattern, i.e. selectors are not pure functions because they trigger side-effects, etc.
We have a least two re-renders, one with an undefined, and an other one when the API responds.
Thanks in advance!
Redux 官方文档中没有讨论在 reselect 中进行调度,因此它不应该被认为是好的解决方案。
但有些解决方案非常接近您想要实现的目标。例如redux-async-loader或将React.Lazy 与 Redux 结合使用。
这两种方法的总体思想是将数据获取转移到connect函数(重新选择所在的位置)。在这个术语中,这两种方法都非常接近您试图通过重新选择中的调度来实现的目标。
从我的角度来看,Redux-async-loader 更简单一些。它创建了环绕 的高阶组件connect。
React.Lazy 的作用本质上是相同的。另外,您可以Suspense在等待数据时使用组件临时显示“数据正在加载...”。