[译] 关于 SPA,你需要掌握的 4 层 (2)

此文已由作者张威授权网易云社区发布。

欢迎访问网易云社区,了解更多网易技术产品运营经验。


视图层

现在我们有了一个可执行且不依赖于框架的应用程序,React 已经准备投入使用。

视图层由 presentational components 和 container components 组成。

presentational components 关注事物的外观,而 container components 则关注事物的工作方式。更多细节解释请关注 Dan Abramov 的文章



让我们使用 ArticleFormContainer 和 ArticleListContainer 开始构建 App 组件。

// @flowimport React, {Component} from 'react';import './App.css';import {ArticleFormContainer} from "./components/ArticleFormContainer";import {ArticleListContainer} from "./components/ArticleListContainer";

type Props = {};class App extends Component<Props> {
  render() {    return (
      <div className="App">
        <ArticleFormContainer/>
        <ArticleListContainer/>
      </div>
    );
  }
}export default App;

接下来,我们来创建 ArticleFormContainer。React 或者 Angular 都不重要,表单有些复杂。

查看 Ramda 库以及如何增强我们代码的声明性质的方法。

表单接受用户输入并将其传递给 articleService 处理。此服务根据该输入创建一个 Article,并将其添加到 ArticleStore 中以供 interested 组件使用它。所有这些逻辑都存储在 submitForm 方法中。


『ArticleFormContainer.js』

// @flowimport React, {Component} from 'react';import * as R from 'ramda';import type {ArticleService} from "../domain/ArticleService";import type {ArticleStore} from "../store/ArticleStore";import {articleService} from "../domain/ArticleService";import {articleStore} from "../store/ArticleStore";import {ArticleFormComponent} from "./ArticleFormComponent";

type Props = {};

type FormField = {  value: string;  valid: boolean;
}

export type FormData = {  articleTitle: FormField;  articleAuthor: FormField;
};

export class ArticleFormContainer extends Component<Props, FormData> {  articleStore: ArticleStore;  articleService: ArticleService;

  constructor(props: Props) {    super(props);    this.state = {      articleTitle: {        value: '',        valid: true
      },      articleAuthor: {        value: '',        valid: true
      }
    };    this.articleStore = articleStore;    this.articleService = articleService;
  }

  changeArticleTitle(event: Event) {    this.setState(
      R.assocPath(
        ['articleTitle', 'value'],
        R.path(['target', 'value'], event)
      )
    );
  }

  changeArticleAuthor(event: Event) {    this.setState(
      R.assocPath(
        ['articleAuthor', 'value'],
        R.path(['target', 'value'], event)
      )
    );
  }

  submitForm(event: Event) {
    const articleTitle = R.path(['target', 'articleTitle', 'value'], event);
    const articleAuthor = R.path(['target', 'articleAuthor', 'value'], event);

    const isTitleValid = this.articleService.isTitleValid(articleTitle);
    const isAuthorValid = this.articleService.isAuthorValid(articleAuthor);    if (isTitleValid && isAuthorValid) {
      const newArticle = this.articleService.createArticle({        title: articleTitle,        author: articleAuthor
      });      if (newArticle) {        this.articleStore.addArticle(newArticle);
      }      this.clearForm();
    } else {      this.markInvalid(isTitleValid, isAuthorValid);
    }
  };

  clearForm() {    this.setState((state) => {      return R.pipe(
        R.assocPath(['articleTitle', 'valid'], true),
        R.assocPath(['articleTitle', 'value'], ''),
        R.assocPath(['articleAuthor', 'valid'], true),
        R.assocPath(['articleAuthor', 'value'], '')
      )(state);
    });
  }

  markInvalid(isTitleValid: boolean, isAuthorValid: boolean) {    this.setState((state) => {      return R.pipe(
        R.assocPath(['articleTitle', 'valid'], isTitleValid),
        R.assocPath(['articleAuthor', 'valid'], isAuthorValid)
      )(state);
    });
  }

  render() {    return (
      <ArticleFormComponent
        formData={this.state}
        submitForm={this.submitForm.bind(this)}
        changeArticleTitle={(event) => this.changeArticleTitle(event)}
        changeArticleAuthor={(event) => this.changeArticleAuthor(event)}
      />
    )
  }
}

这里注意 ArticleFormContainer,presentational component,返回用户看到的真实表单。该组件显示容器传递的数据,并抛出 changeArticleTitle、 changeArticleAuthor 和 submitForm 的方法。


ArticleFormComponent.js

// @flow
import React from 'react';

import type {FormData} from './ArticleFormContainer';

type Props = {
  formData: FormData;
  changeArticleTitle: Function;
  changeArticleAuthor: Function;
  submitForm: Function;
}

export const ArticleFormComponent = (props: Props) => {
  const {
    formData,
    changeArticleTitle,
    changeArticleAuthor,
    submitForm
  } = props;

  const onSubmit = (submitHandler) => (event) => {
    event.preventDefault();
    submitHandler(event);
  };

  return (    <form
      noValidate
      onSubmit={onSubmit(submitForm)}
    >
      <div>
        <label htmlFor="article-title">Title</label>
        <input
          type="text"
          id="article-title"
          name="articleTitle"
          autoComplete="off"
          value={formData.articleTitle.value}
          onChange={changeArticleTitle}
        />
        {!formData.articleTitle.valid && (<p>Please fill in the title</p>)}      </div>
      <div>
        <label htmlFor="article-author">Author</label>
        <input
          type="text"
          id="article-author"
          name="articleAuthor"
          autoComplete="off"
          value={formData.articleAuthor.value}
          onChange={changeArticleAuthor}
        />
        {!formData.articleAuthor.valid && (<p>Please fill in the author</p>)}      </div>
      <button
        type="submit"
        value="Submit"
      >
        Create article      </button>
    </form>
  )
};

现在我们有了创建文章的表单,下面就陈列他们吧。ArticleListContainer 订阅了 ArticleStore,获取所有的文章并展示在 ArticleListComponent 中。


『ArticleListContainer.js』

// @flowimport * as React from 'react'import type {Article} from "../domain/Article";import type {ArticleStore} from "../store/ArticleStore";import {articleStore} from "../store/ArticleStore";import {ArticleListComponent} from "./ArticleListComponent";

type State = {  articles: Article[]
}

type Props = {};

export class ArticleListContainer extends React.Component<Props, State> {  subscriber: Function;  articleStore: ArticleStore;

  constructor(props: Props) {    super(props);    this.articleStore = articleStore;    this.state = {      articles: []
    };    this.subscriber = this.articleStore.subscribe((articles: Article[]) => {      this.setState({articles});
    });
  }

  componentWillUnmount() {    this.articleStore.unsubscribe(this.subscriber);
  }

  render() {    return <ArticleListComponent {...this.state}/>;
  }
}

ArticleListComponent 是一个 presentational component,他通过 props 接收文章,并展示组件 ArticleContainer。


『ArticleListComponent.js』

// @flowimport React from 'react';import type {Article} from "../domain/Article";import {ArticleContainer} from "./ArticleContainer";

type Props = {  articles: Article[]
}export const ArticleListComponent = (props: Props) => {  const {articles} = props;  return (
    <div>
      {
        articles.map((article: Article, index) => (
          <ArticleContainer
            article={article}
            key={index}
          />
        ))
      }
    </div>
  )
};

ArticleContainer 传递文章数据到表现层的 ArticleComponent,同时实现 likeArticle 和 removeArticle 这两个方法。

likeArticle 方法负责更新文章的收藏数,通过将现存的文章替换成更新后的副本。

removeArticle 方法负责从 store 中删除制定文章。


『ArticleContainer.js』

// @flowimport React, {Component} from 'react';import type {Article} from "../domain/Article";import type {ArticleService} from "../domain/ArticleService";import type {ArticleStore} from "../store/ArticleStore";import {articleService} from "../domain/ArticleService";import {articleStore} from "../store/ArticleStore";import {ArticleComponent} from "./ArticleComponent";

type Props = {  article: Article;
};

export class ArticleContainer extends Component<Props> {  articleStore: ArticleStore;  articleService: ArticleService;

  constructor(props: Props) {    super(props);    this.articleStore = articleStore;    this.articleService = articleService;
  }

  likeArticle(article: Article) {
    const updatedArticle = this.articleService.updateLikes(article, article.likes + 1);    this.articleStore.updateArticle(updatedArticle);
  }

  removeArticle(article: Article) {    this.articleStore.removeArticle(article);
  }

  render() {    return (
      <div>
        <ArticleComponent
          article={this.props.article}
          likeArticle={(article: Article) => this.likeArticle(article)}
          deleteArticle={(article: Article) => this.removeArticle(article)}
        />
      </div>
    )
  }
}

ArticleContainer 负责将文章的数据传递给负责展示的 ArticleComponent,同时负责当 「收藏」或「删除」按钮被点击时在响应的回调中通知 container component。

还记得那个作者名要大写的无厘头需求吗?

ArticleComponent 在应用程序层调用 ArticleUiService,将一个状态从其原始值(没有大写规律的字符串)转换成一个所需的大写字符串。


『ArticleComponent.js』

// @flowimport React from 'react';import type {Article} from "../domain/Article";import * as articleUiService from "../services/ArticleUiService";

type Props = {  article: Article;  likeArticle: Function;  deleteArticle: Function;
}export const ArticleComponent = (props: Props) => {  const {
    article,
    likeArticle,
    deleteArticle
  } = props;  return (
    <div>
      <h3>{article.title}</h3>
      <p>{articleUiService.displayAuthor(article.author)}</p>
      <p>{article.likes}</p>
      <button
        type="button"
        onClick={() => likeArticle(article)}
      >
        Like
      </button>
      <button
        type="button"
        onClick={() => deleteArticle(article)}
      >
        Delete
      </button>
    </div>
  );
};

干得漂亮!

我们现在有一个功能完备的 React 应用程序和一个鲁棒的、定义清晰的架构。任何新晋成员都可以通过阅读这篇文章学会如何顺利的进展我们的工作。:)


你可以在这里查看我们最终实现的应用程序,同时奉上 GitHub 仓库地址

       

免费体验云安全(易盾)内容安全、验证码等服务

更多网易技术、产品、运营经验分享请点击


相关文章:
【推荐】 Docker 的优势

原文地址:https://www.cnblogs.com/163yun/p/9990815.html