使用 mern.io 脚手架工具 - .need 方法到底是啥?

Posted

技术标签:

【中文标题】使用 mern.io 脚手架工具 - .need 方法到底是啥?【英文标题】:Using mern.io scaffolder tool - What is the .need method all about?使用 mern.io 脚手架工具 - .need 方法到底是什么? 【发布时间】:2016-06-07 11:09:16 【问题描述】:

基于脚手架mern.io,我正在查看代码以查看发生了什么。我偶然发现了一个 .need 方法,它看起来像是与 es6 类相关的东西。我似乎在任何地方都找不到任何可用的信息,所以我问.need 方法是什么?

class PostContainer extends Component 
   //do class setup stuff here


PostContainer.need = [() =>  return Actions.fetchPosts(); ];

您可以使用这些命令轻松启动和运行项目。

npm install -g mern-cli
mern YourAppName

【问题讨论】:

【参考方案1】:

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;

【讨论】:

很好的答案!非常感谢!现在更有意义了。

以上是关于使用 mern.io 脚手架工具 - .need 方法到底是啥?的主要内容,如果未能解决你的问题,请参考以下文章

用vue快速开发app的脚手架工具

使用vue脚手架工具搭建vue-webpack项目

使用vue-cli脚手架工具搭建vue-webpack项目(转)

yeoman简介与基础使用

创建自己的脚手架工具

React 脚手架的使用