Skip to content

Instantly share code, notes, and snippets.

@yesmeck
Last active October 30, 2015 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yesmeck/915dc6ef76806d65d5e0 to your computer and use it in GitHub Desktop.
Save yesmeck/915dc6ef76806d65d5e0 to your computer and use it in GitHub Desktop.
Normalizr 的意义

假设有个 API /articles 返回的结构如下:

articles: article*

article: {
  author: user,
  likers: user*
  primary_collection: collection?
  collections: collection*
}

collection: {
  curator: user
}

你的 component 如下:

class Article extends Component {
  render() {
    return (
      <div>
        <h1>{article.name}</h1>

        {article.likers.map(liker =>
          <User user={liker} />
        }
      </div>
    );
  }
}

如果你把 API 返回的结果直接存在 store 里,那么 liker 的信息是嵌套存在 article 里的,如果你有一个 users store 存了用户信息,然后更新了其中用户的信息后,存在 article store 的 user 是无法知道这个变化。

Normalizr 把嵌套的 JSON 拍平后,article 的 liker 信息可以放倒 users.store 里,这样就解决了上面的问题。

这样还能减少存在 store 里的数据。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment