mern 文档在解释这一点时非常简洁。
fetchComponentData 收集当前路由中组件的所有needs(need 是在渲染组件之前需要调度的一系列操作)。当所有必需的操作都被调度时,它会返回一个 Promise。
通读代码可以更清楚地了解这里发生了什么。
概述
这是一种指定在渲染组件之前应该调度的一些操作的方法。
该组件将 Redux 存储中的 posts 属性映射到名为 posts 的属性,以便它可以呈现帖子列表。
// PostContainer.jsx
function mapStateToProps(store) {
return {
posts: store.posts,
};
}
但是,最初此属性将为空,因为需要从异步 API 获取帖子。
// reducer.js
// initial state of the store is an empty array
const initialState = { posts: [], selectedPost: null };
此组件需要在渲染之前发布可用的帖子,因此它将调用返回的操作分派给Actions.fetchPosts()。
// actions.js
export function fetchPosts() {
return (dispatch) => {
return fetch(`${baseURL}/api/getPosts`).
then((response) => response.json()).
then((response) => dispatch(addPosts(response.posts)));
};
}
action 完成调度后,可以将 store 的数据映射到连接的组件。
警告
这不是为 React 组件指定异步依赖的通用方法。它之所以有效,是因为 mern 有一个名为 fetchComponentData 的实用方法,它在服务器端调用,以便在渲染之前填充 Redux 存储。
// server.js
fetchComponentData(store.dispatch, renderProps.components, renderProps.params)
此方法遍历第二个参数中的组件以从中提取needs。然后它执行 'needs` 并等待所有的 Promise 完成。
// fetchData.js
const promises = needs.map(need => dispatch(need(params)));
return Promise.all(promises);
当Promise.all(promise) 返回的承诺完成时,Redux 存储将被填充,并且组件可以安全地呈现它们的数据以提供给客户端。
语法
你提到你认为它可能与 ES6 类有关,所以我也会快速介绍一下语法。
ES6 类不能在类字面量中指定静态属性,而是必须在类定义后将它们声明为类的属性。
needs 属性必须是返回 Promise 以与 fetchComponentData 一起使用的函数数组。在这种情况下,我们在数组文字中声明了一个箭头函数。将其拆分为单独的变量可能会有所帮助。
const fetchPosts = () => { return Actions.fetchPosts() };
const needs = [fetchPosts];
PostContainer.need = needs;