{"id":20064881,"url":"https://github.com/baidu/san-store","last_synced_at":"2026-03-07T17:31:29.161Z","repository":{"id":18020399,"uuid":"81430106","full_name":"baidu/san-store","owner":"baidu","description":"Application States Management for San","archived":false,"fork":false,"pushed_at":"2025-01-09T07:23:53.000Z","size":2100,"stargazers_count":63,"open_issues_count":9,"forks_count":35,"subscribers_count":16,"default_branch":"master","last_synced_at":"2026-03-03T13:13:34.452Z","etag":null,"topics":["appstate","san"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/baidu.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-02-09T08:58:17.000Z","updated_at":"2026-02-01T19:29:08.000Z","dependencies_parsed_at":"2024-06-18T18:23:31.302Z","dependency_job_id":"6aa55949-8805-4b0d-8ad8-5ed84bb45c9b","html_url":"https://github.com/baidu/san-store","commit_stats":{"total_commits":250,"total_committers":16,"mean_commits":15.625,"dds":"0.41600000000000004","last_synced_commit":"0e54932fe75593171d251d03ccc8f194dc0ed19a"},"previous_names":["ecomfe/san-store"],"tags_count":25,"template":false,"template_full_name":null,"purl":"pkg:github/baidu/san-store","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baidu%2Fsan-store","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baidu%2Fsan-store/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baidu%2Fsan-store/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baidu%2Fsan-store/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/baidu","download_url":"https://codeload.github.com/baidu/san-store/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/baidu%2Fsan-store/sbom","scorecard":{"id":223855,"data":{"date":"2025-08-11","repo":{"name":"github.com/baidu/san-store","commit":"143f1d34c90876cc5b7805a3e12f6def74018170"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":2.7,"checks":[{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Code-Review","score":2,"reason":"Found 5/22 approved changesets -- score normalized to 2","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/ci.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/baidu/san-store/ci.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/baidu/san-store/ci.yml/master?enable=pin","Warn: npmCommand not pinned by hash: .github/workflows/ci.yml:19","Info:   0 out of   2 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   1 npmCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: MIT License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'master'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 13 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":0,"reason":"97 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: GHSA-968p-4wvh-cqc8","Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92","Warn: Project is vulnerable to: GHSA-whgm-jr23-g3j9","Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw","Warn: Project is vulnerable to: GHSA-qwcr-r2fm-qrc7","Warn: Project is vulnerable to: GHSA-v6h2-p8h4-qcjw","Warn: Project is vulnerable to: GHSA-cwfw-4gq5-mrqx","Warn: Project is vulnerable to: GHSA-g95f-p29q-9xw4","Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg","Warn: Project is vulnerable to: GHSA-x9w5-v3q2-3rhw","Warn: Project is vulnerable to: GHSA-pxg6-pf52-xh8x","Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275","Warn: Project is vulnerable to: GHSA-9vvw-cc9w-f27h","Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c","Warn: Project is vulnerable to: GHSA-w573-4hg7-7wgq","Warn: Project is vulnerable to: GHSA-434g-2637-qmqr","Warn: Project is vulnerable to: GHSA-49q7-c7j4-3p7m","Warn: Project is vulnerable to: GHSA-977x-g7h5-7qgw","Warn: Project is vulnerable to: GHSA-f7q4-pwc6-w24p","Warn: Project is vulnerable to: GHSA-fc9h-whq2-v747","Warn: Project is vulnerable to: GHSA-vjh7-7g9h-fjfh","Warn: Project is vulnerable to: GHSA-j4f2-536g-r55m","Warn: Project is vulnerable to: GHSA-r7qp-cfhv-p84w","Warn: Project is vulnerable to: GHSA-6h5x-7c5m-7cr7","Warn: Project is vulnerable to: GHSA-rv95-896h-c2vc","Warn: Project is vulnerable to: GHSA-qw6h-vgh9-j6wx","Warn: Project is vulnerable to: GHSA-jchw-25xp-jwwc","Warn: Project is vulnerable to: GHSA-cxjh-pqwp-8mfp","Warn: Project is vulnerable to: GHSA-c7qv-q95q-8v27","Warn: Project is vulnerable to: GHSA-qqgx-2p2h-9c37","Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22","Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp","Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h","Warn: Project is vulnerable to: GHSA-7x7c-qm48-pq9c","Warn: Project is vulnerable to: GHSA-rc3x-jf5g-xvc5","Warn: Project is vulnerable to: GHSA-6c8f-qphg-qjgp","Warn: Project is vulnerable to: GHSA-76p3-8jx3-jpfq","Warn: Project is vulnerable to: GHSA-3rfm-jhwj-7488","Warn: Project is vulnerable to: GHSA-hhq3-ff78-jv3g","Warn: Project is vulnerable to: GHSA-jf85-cpcp-j695","Warn: Project is vulnerable to: GHSA-fvqr-27wr-82fm","Warn: Project is vulnerable to: GHSA-4xc9-xhrj-v574","Warn: Project is vulnerable to: GHSA-x5rq-j2xg-h7qm","Warn: Project is vulnerable to: GHSA-p6mc-m468-83gw","Warn: Project is vulnerable to: GHSA-29mw-wpgm-hmr9","Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm","Warn: Project is vulnerable to: GHSA-82v2-mx6x-wq7q","Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv","Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3","Warn: Project is vulnerable to: GHSA-vh95-rmgr-6w4m","Warn: Project is vulnerable to: GHSA-xvch-5gv4-984h","Warn: Project is vulnerable to: GHSA-w9mr-4mfr-499f","Warn: Project is vulnerable to: GHSA-92xj-mqp7-vmcj","Warn: Project is vulnerable to: GHSA-wxgw-qj99-44c2","Warn: Project is vulnerable to: GHSA-5rrq-pxf6-6jx5","Warn: Project is vulnerable to: GHSA-8fr3-hfg3-gpgp","Warn: Project is vulnerable to: GHSA-gf8q-jrpm-jvxq","Warn: Project is vulnerable to: GHSA-2r2c-g63r-vccr","Warn: Project is vulnerable to: GHSA-cfm4-qjh2-4765","Warn: Project is vulnerable to: GHSA-x4jg-mjrx-434g","Warn: Project is vulnerable to: GHSA-76c9-3jph-rj3q","Warn: Project is vulnerable to: GHSA-q75g-2496-mxpp","Warn: Project is vulnerable to: GHSA-6fx8-h7jm-663j","Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j","Warn: Project is vulnerable to: GHSA-rhx6-c78j-4q9w","Warn: Project is vulnerable to: GHSA-h7cp-r72f-jxh6","Warn: Project is vulnerable to: GHSA-v62p-rq8g-8h59","Warn: Project is vulnerable to: GHSA-hrpp-h998-j3pp","Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm","Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw","Warn: Project is vulnerable to: GHSA-m6fv-jmcg-4jfg","Warn: Project is vulnerable to: GHSA-hxcc-f52p-wc94","Warn: Project is vulnerable to: GHSA-cm22-4g7w-348p","Warn: Project is vulnerable to: GHSA-fxwf-4rqh-v8g3","Warn: Project is vulnerable to: GHSA-25hc-qcg6-38wj","Warn: Project is vulnerable to: GHSA-xfhh-g9f5-x4m4","Warn: Project is vulnerable to: GHSA-qm95-pgcg-qqfq","Warn: Project is vulnerable to: GHSA-cqmj-92xf-r6r9","Warn: Project is vulnerable to: GHSA-c9g6-9335-x697","Warn: Project is vulnerable to: GHSA-3jfq-g458-7qm9","Warn: Project is vulnerable to: GHSA-r628-mhmh-qjhw","Warn: Project is vulnerable to: GHSA-9r2w-394v-53qc","Warn: Project is vulnerable to: GHSA-5955-9wpr-37jh","Warn: Project is vulnerable to: GHSA-qq89-hq3f-393p","Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36","Warn: Project is vulnerable to: GHSA-4wf5-vphf-c2xc","Warn: Project is vulnerable to: GHSA-52f5-9888-hmc6","Warn: Project is vulnerable to: GHSA-mgfv-m47x-4wqp","Warn: Project is vulnerable to: GHSA-wr3j-pwj9-hqq6","Warn: Project is vulnerable to: GHSA-4v9v-hfq4-rm2v","Warn: Project is vulnerable to: GHSA-9jgg-88mc-972h","Warn: Project is vulnerable to: GHSA-5v72-xg48-5rpm","Warn: Project is vulnerable to: GHSA-6fc8-4gx4-v693","Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q","Warn: Project is vulnerable to: GHSA-72mh-269x-7mh5","Warn: Project is vulnerable to: GHSA-h4j5-c7cj-74xg","Warn: Project is vulnerable to: GHSA-p9pc-299p-vxgp"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-17T03:12:25.590Z","repository_id":18020399,"created_at":"2025-08-17T03:12:25.590Z","updated_at":"2025-08-17T03:12:25.590Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30223248,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-07T17:00:40.062Z","status":"ssl_error","status_checked_at":"2026-03-07T17:00:39.026Z","response_time":53,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["appstate","san"],"created_at":"2024-11-13T13:48:05.610Z","updated_at":"2026-03-07T17:31:29.131Z","avatar_url":"https://github.com/baidu.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# san-store\n\n[![NPM version](http://img.shields.io/npm/v/san-store.svg?style=flat-square)](https://npmjs.org/package/san-store)\n[![License](https://img.shields.io/github/license/baidu/san-store.svg?style=flat-square)](https://npmjs.org/package/san-store)\n[![Build Status](https://github.com/baidu/san-store/workflows/CI/badge.svg)](https://github.com/baidu/san-store/actions)\n\n[San](https://baidu.github.io/san/) 框架的官方应用状态管理套件，其理念是类似 flux 的单向流。\n\n虽然应用状态管理已经是流行的理念，我们依然推荐您在开始之前，先看看 [为什么要进行应用状态管理](https://github.com/baidu/san-store/blob/master/doc/why-use-store.md)，可能会有些思考和启发。\n\n![flow](https://raw.githubusercontent.com/baidu/san-store/master/doc/flow.png)\n\n\u003e 提示：使用 san-store 需要同时使用 [san-update](https://github.com/baidu/san-update) 2.x 创建状态变更器，san-store 将使用此变更器更新 store 中的应用状态。\n\n- [下载](#下载)\n- [使用](#使用)\n- [单Store与多Store](#单store与多store) \n- [Action](#action) \n- [组件的connect](#组件的connect) \n- [API](https://github.com/baidu/san-store/blob/master/doc/api.md)\n\n\n下载\n----\n\nNPM:\n\n```\n$ npm i --save san-store san-update\n```\n\n\n使用\n----\n\n```javascript\nimport {store, connect} from 'san-store';\nimport {builder} from 'san-update';\n\n\nstore.addAction('changeUserName', function (name) {\n    return builder().set('user.name', name);\n});\n\n\nlet UserNameEditor = connect({\n    name: 'user.name'\n})(san.defineComponent({\n    submit() {\n        store.dispatch('changeUserName', this.data.get('name'));\n    }\n}));\n```\n\n\n从例子开始和模仿比死啃枯燥的文档要更人性化。 [Todos项目](https://github.com/baidu/san-store/tree/master/example/todos) 和 [RealWorld App](https://github.com/ecomfe/san-realworld-app) 展示了如何在项目里使用 san-store 进行状态管理。\n[多store的Todos项目](https://github.com/baidu/san-store/tree/master/example/todos-multiple-store) 展示了如何再项目中使用 多 store connect 及 [composition api](https://github.com/baidu/san-composition) 的用法。\n\n本文档描述了 san-store 的基本使用场景。想了解 san-store 都提供了什么，可以参阅 [API文档](https://github.com/baidu/san-store/tree/master/doc/api.md)\n\n\n单Store与多Store\n----\n\n一个应用具有唯一的应用状态源，在一个地方管理整个应用的所有状态，是一个比较共识的方式。所以 san-store 提供了默认的 Store 实例。绝大多数时候，应用开发者不需要手工创建自己的 Store 实例，只需要 import 默认的 store。\n\n\n```javascript\nimport {store} from 'san-store';\n\n// 通过 getState 方法，获取 store 中的状态数据。\nconsole.log(store.getState('user.name'));\n```\n\n[store](https://github.com/baidu/san-store/blob/master/doc/api.md#store) 并没有提供修改状态数据的方法，修改状态数据只能通过 [dispatch](https://github.com/baidu/san-store/blob/master/doc/api.md#dispatch) action 来做到，具体细节请参考 [Action](#action) 章节。通过 [addAction](https://github.com/baidu/san-store/blob/master/doc/api.md#addaction) 方法可以添加 action。\n\n```javascript\nstore.addAction('changeUserName', name =\u003e builder().set('user.name', name));\n```\n\n\n当同一系统中有不同团队开发自己的业务模块，各团队之间没有状态共享，可以考虑分别建立 Store 实例进行开发。通过 new Store 创建自己的 Store 实例。创建时可以传入初始化数据和声明 actions。\n\n```javascript\nimport {Store} from 'san-store';\nimport {builder} from 'san-update';\n\n\nlet myStore = new Store({\n    initData: {\n        user: {\n            name: 'your name'\n        }\n    },\n\n    actions: {\n        changeUserName(name) {\n            return builder().set('user.name', name);\n        }\n    }\n});\n```\n\n本节最后，还是要强调下，应用开发应当遵循 **一个应用具有唯一的应用状态源**。说白了就是 **要按常理出牌**。\n\n\nAction\n----\n\n通过 [addAction](https://github.com/baidu/san-store/blob/master/doc/api.md#addaction) 方法可以为 [Store](https://github.com/baidu/san-store/blob/master/doc/api.md#store) 添加 Action。 Action 是 san-store 最重要的组成部分之一，它：\n\n1. 是一个函数\n1. 在一个 [store](https://github.com/baidu/san-store/blob/master/doc/api.md#store) 内每个 action 具有唯一名称，通过名称 [dispatch](https://github.com/baidu/san-store/blob/master/doc/api.md#dispatch)\n1. 是 [store](https://github.com/baidu/san-store/blob/master/doc/api.md#store) 更新状态的唯一入口\n1. 状态更新是同步的，这使得状态更新可依赖当前状态环境，可被记录、被追溯和重放\n\n\n如果你使用了 san-store，**Action 应该是你业务组件的唯一出口**：用户操作事件等需要改变应用状态时，都应该 dispatch Action。\n\n### 变更应用状态\n\n\nAction 接收一个 payload，返回一个 [san-update](https://github.com/baidu/san-update) 的 builder 对象。store 使用 builder 对象生成状态变更函数，并执行它，使 store 内部的状态得到更新。当然，如果当前 action 不期望对 store 的状态进行更新，可以不返回 builder 对象。\n\n```javascript\nimport {builder} from 'san-update';\n\nstore.addAction('changeUserName', function (name) {\n    return builder().set('user.name', name);\n});\n\n// 通过名称 dispatch\nstore.dispatch('changeUserName', 'erik');\n```\n\n\nsan-update 是一个 Immutable 的更新对象库，其提供了一些更新函数（如set、push等），通过 `newObj = set(oldObj, 'x', 1)` 的使用形式让对象更新 Immutable。builder 是 san-update 提供的一个很好用的功能，通过 builder 你可以预定义一系列的数据更新操作，然后通过 `builder.build` 方法可以获得一个更新函数。san-store 就是利用这个功能，使用 action 返回的 builder 生成对象更新函数，再调用它进行 store 内部状态更新。\n\nsan-update 的 builder 支持预定义所有 san-update 支持的数据操作，通过 [san-update文档：可用指令](https://github.com/baidu/san-update#可用指令) 可以查看所有操作类型。常用的有：\n\n- apply: 对现有数据项应用更新\n- set: 设置数据项\n- remove: 数组移除项\n- push: 数组push操作\n- pop: 数组pop操作\n- unshift: 数组unshift操作\n- shift: 数组shift操作\n- splice: 数组splice操作\n\n\n使用前请阅读 [san-update文档：使用builder构建更新函数](https://github.com/baidu/san-update#使用builder构建更新函数) 进行详细了解。\n\n\n### 获取当前应用状态\n\nAction 的第二个参数是一个对象，其中的 getState 方法可以用于获得当前 store 中的应用状态。这个方法是 this 无关的。\n\n\n```javascript\nimport {builder} from 'san-update';\n\nstore.addAction('initCount', function (count, {getState}) {\n    if (getState('count') == null) {\n        return builder().set('count', count);\n    }\n});\n\nstore.dispatch('initCount', 10);\n```\n\n如果我们的更新操作仅依赖于当前数据状态项的值，也可以使用 [san-update](https://github.com/baidu/san-update) 提供的 apply 方法。\n\n\n```javascript\nimport {builder} from 'san-update';\n\nstore.addAction('initCount', function (count) {\n    // apply 意思是：在原有的值上应用新的值\n    return builder().apply('count', oldValue =\u003e {\n        return oldValue == null ? count : oldValue;\n    });\n});\n\nstore.dispatch('initCount', 10);\n```\n\n### 异步过程\n\n同步的 Action 返回一个 builder，并立即更新数据状态，但我们经常会遇到异步的场景，常见的比如请求数据、返回并更新应用状态。Action 在设计上作为 **业务组件的唯一出口**， 对异步支持的方式如下：\n\n1. 返回一个 Promise 时，当前 Action 为异步\n2. 返回一个 builder 或什么都不返回时，当前 Action 为同步\n\n下面是一个简单的例子： 一个列表请求的行为，此时要显示 loading，在请求返回时更新应用状态中的列表项，同时隐藏 loading。\n\n```javascript\nimport {builder} from 'san-update';\n\nstore.addAction('fetchList', function (page, {getState, dispatch}) {\n    dispatch('showLoading');\n    dispatch('updateCurrentPage', page);\n\n    return requestList(page).then(list =\u003e {\n        if (getState('currentPage') === page) {\n            dispatch('updateList', list);\n            dispatch('hideLoading');\n        }\n    });\n});\n\nstore.addAction('showLoading', function () {\n    return builder().set('loading', true);\n});\n\nstore.addAction('hideLoading', function () {\n    return builder().set('loading', false);\n});\n\nstore.addAction('updateCurrentPage', function (page) {\n    return builder().set('currentPage', page);\n});\n\nstore.addAction('updateList', function (list) {\n    return builder().set('list', list);\n});\n\n\n// 这里模拟一下，意思意思\nfunction requestList(page) {\n    return new Promise(resolve =\u003e {\n        setTimeout(() =\u003e {\n            let pageList = [1, 2, 3];\n            resolve(pageList);\n        }, 500);\n    });\n}\n```\n\n例子中有下面几个要点：\n\n1. 异步 Action 可以多次 dispatch 其他的 Action，通过第二个参数对象中的 dispatch 方法。这个方法和 getState 一样，也是 this 无关的。\n2. fetchList 中马上 updateCurrentPage，在请求返回时使用 getState 方法对 currentPage 判断，能够避免用户快速多次点击页码时发起多个 list 请求，请求返回的顺序不同可能导致问题。\n3. 异步 Action 没有更新应用状态的能力，想要更新应用状态必须 dispatch 同步 Action。下面的代码说明了为什么，感兴趣可以看看。\n\n```javascript\nstore.addAction('fetchList', function (page, {getState, dispatch}) {\n    dispatch('showLoading');\n    dispatch('updateCurrentPage', page);\n\n    return requestList(page).then(list =\u003e {\n        if (getState('currentPage') === page) {\n            dispatch('hideLoading');\n            \n            // 如果异步 Action 支持在 promise 中返回 builder 并更新状态\n            // 这里的代码就可能导致问题。因为 promise.then 不是马上运行的\n            // 这里的 currentPage 不代表 builder 运行时的 currentPage\n            // currentPage 可能被另外一个 dispatch fetchList 改掉\n            // 所以这里应该 dispatch 一个同步的 Action 让应用状态即时完成变更\n            dispatch('updateList', list);  // good\n            // return builder().set('list', list); // warning\n        }\n    });\n});\n```\n\n异步 Action 在 dispatch 时将返回 Promise 对象，以便于 Action 完成后的逻辑控制。\n\n```javascript\nstore.addAction('addArticle', function (article) {\n    return axios.post(url, article);\n});\n\n\nstore.dispatch('addArticle', {}).then(() =\u003e {\n    // redirect to view page\n});\n```\n\n\n组件的connect\n----\n\n### connect到默认store\n\n[connect](https://github.com/baidu/san-store/blob/master/doc/api.md#connect-1) 方法支持对 **默认store实例** 和 [San](https://baidu.github.io/san/) 组件进行连接，步骤和 redux 类似：\n\n1. 通过 [connect](https://github.com/baidu/san-store/blob/master/doc/api.md#connect-1) 方法创建一个 connect 组件的函数\n2. 调用这个函数对组件进行 connect\n\n```javascript\nimport {store, connect} from 'san-store';\n\nconst connector = connect(\n    {name: 'user.name'},\n    {change: 'changeUserName'}\n);\nconst UserNameEditor = san.defineComponent({/*...*/});\nconst NewUserNameEditor = connector(UserNameEditor);\n```\n\n通常，我们只需要对当前声明的组件进行 connect。此时可以合并成一句\n\n```javascript\nconst UserNameEditor = san.defineComponent({/*...*/});\nconst NewUserNameEditor = connect(\n    {name: 'user.name'},\n    {change: 'changeUserName'}\n)(UserNameEditor);\n```\n\n### connect到自己创建的store\n\n当实际业务中需要多个 Store 实例时，可以自行创建 Store 实例。connect 方法支持连接到指定的 Store 实例。\n\n```js\nimport {Store, connect} from 'san-store';\n\n// 自行创建 store 实例\nconst myStore = new Store({\n    initData: {\n        name:'erik'\n    },\n    actions:{\n        changeUserName(name) {\n            return builder().set('user.name', name);\n        }\n    }\n});\n\nconst UserNameEditor = san.defineComponent({/*...*/});\n\n// connect 时提供自创建的 storeA \nconst NewUserNameEditor = connect(\n    myStore,\n    {name: 'user.name'},\n    {change: 'changeUserName'}\n)(UserNameEditor);\n```\n\n### 映射store状态与组件data\n\n`mapStates` 参数指定了要把哪些状态注入到组件，key 是要注入到组件的数据项名称，value 是 store 中状态项的名称。\n\n```javascript\nimport {store, connect} from 'san-store';\n\nconst NewUserNameEditor = connect(\n    {name: 'user.name'}\n)(san.defineComponent({\n    // connect 后，name 数据项由 store 提供\n    template: '\u003cdiv title=\"{{name}}\"\u003e......\u003c/div\u003e'\n}));\n```\n\n\n### 组件上可直接调用的 dispatch action 方法\n\n使用 store 时，我们可以通过调用 `store.dispatch(actionName, payload)` 方法更新应用状态。但如果在组件中也这么做，就会有些问题：\n\n- 由于 actionName 的应用全局唯一性，名字需要比较完整，对于组件来说这么长的名称会显得比较冗余\n- 组件实现时，得关心对具体 store 的依赖\n\n通过指定 `mapActions` 可以在组件的 actions 成员上生成 dispatch action 的快捷方法，让组件可以更便捷的 dispatch action。`mapActions` 的 key 是要映射到组件 actions 成员上的方法名，value 是 action 的名称。\n\n\n```javascript\nimport {store, connect} from 'san-store';\n\nconst UserNameEditor = connect(\n    {name: 'user.name'},\n    {change: 'changeUserName'}\n)(san.defineComponent({\n    submit() {\n        // 通过 mapActions，可以把 dispatch action 简化成组件自身的方法调用\n        // store.dispatch('changeUserName', this.data.get('name'));\n        this.actions.change(this.data.get('name'));\n    }\n}));\n```\n\n### connect 多个 store\n\n当实际业务中真的需要多个 Store 实例时，可以通过 [connect](https://github.com/baidu/san-store/blob/master/doc/api.md#connect-1) 自行创建 connector，连接 Store 实例和 San 组件。步骤如下：\n\n1. 创建 Store 实例\n2. 通过 [connect().connect()](https://github.com/baidu/san-store/blob/master/doc/api.md#connect-1) 方式，即 connect 的链式调用实现 连接多个 store\n\n```js\nimport {Store, connect} from 'san-store';\n\n// 创建模块A中的store实例\nconst storeA = new Store({\n    initData: {\n        name:'erik'\n    },\n    actions:{\n        changeUserName(name) {\n            return builder().set('user.name', name);\n        }\n    }\n});\n\nconst storeB = new Store({\n    initData: {\n        todos: []\n    },\n    actions:{\n        changeTodos(payload) {\n            return builder().set('todos', payload);\n        }\n    }\n});\n\nconst Container = san.defineComponent({/*...*/});\n\n// 调用手动创建的connectA方法进行storeA和组件连接\nconst NewContainer = connect(\n    storeA,\n    {name: 'user.name'},\n    {change: 'changeUserName'}\n).connect(\n    storeB,\n    {todos: 'todos'},\n    ['changeTodos']\n)(Container);\n```\n\n### componsition api\n\n\n[use api](https://github.com/baidu/san-store/blob/master/doc/api.md#use) 提供了对 [san-composition](https://github.com/baidu/san-composition) 形式组件的 store 支持：\n\n1. 使用 `useState` 定义数据。\n2. 使用 `useAction` 定义方法。\n\n```js\nimport san from 'san';\nimport {defineComponent, template, method} from 'san-composition';\nimport {useState} from 'san-store/use';\nimport {Store} from 'san-store';\n\n// 创建模块A中的store实例\nconst myStore = new Store({\n    initData: {\n        name:'erik'\n    },\n    actions:{\n        changeUserName(name) {\n            return builder().set('user.name', name);\n        }\n    }\n});\n\nexport default defineComponent(context =\u003e {\n    template(`\n        \u003cdiv\u003e{{name}}\n            \u003cinput value=\"{=newName=}\"\u003e\u003cbutton on-click=\"change\"\u003echange\u003c/button\u003e\n        \u003c/div\u003e\n    `);\n\n    const name = useState(myStore, 'user.name', 'name');\n    const newName = data('newName', '');\n    let changeUserName = useAction(myStore, 'changeUserName');\n\n    method({\n        change: () =\u003e {\n            changeUserName(newName.get());\n        }\n    });\n\n}, san);\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbaidu%2Fsan-store","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbaidu%2Fsan-store","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbaidu%2Fsan-store/lists"}