@abuffseagull/unistore 中文文档教程
unistore
- Small footprint complements Preact nicely (unistore + unistore/preact is ~650b)
- Familiar names and ideas from Redux-like libraries
- Useful data selectors to extract properties from state
- Portable actions can be moved into a common place and imported
- Functional actions are just reducers
- NEW: seamlessly run Unistore in a worker via Stockroom
Table of Contents
Install
该项目使用 node 和 npm。 如果您没有在本地安装它们,请检查它们。
npm install --save unistore
然后使用像 webpack 或 rollup 这样的模块打包器,作为你会做任何其他事情:
// The store:
import createStore from 'unistore'
// Preact integration
import { Provider, connect } from 'unistore/preact'
// React integration
import { Provider, connect } from 'unistore/react'
或者,你可以为每个导入“完整”构建,其中包括 createStore
和你选择的库的集成:
import { createStore, Provider, connect } from 'unistore/full/preact'
<!-- just unistore(): -->
<script src="https://unpkg.com/unistore/dist/unistore.umd.js"></script>
<!-- for preact -->
<script src="https://unpkg.com/unistore/full/preact.umd.js"></script>
<!-- for react -->
<script src="https://unpkg.com/unistore/full/react.umd.js"></script>
您可以在 window.unistore< 上找到该库/代码>。
Usage
import createStore from 'unistore'
import { Provider, connect } from 'unistore/preact'
let store = createStore({ count: 0, stuff: [] })
let actions = {
// Actions can just return a state update:
increment(state) {
// The returned object will be merged into the current state
return { count: state.count+1 }
},
// The above example as an Arrow Function:
increment2: ({ count }) => ({ count: count+1 }),
// Actions receive current state as first parameter and any other params next
// See the "Increment by 10"-button below
incrementBy: ({ count }, incrementAmount) => {
return { count: count+incrementAmount }
},
}
// If actions is a function, it gets passed the store:
let actionFunctions = store => ({
// Async actions can be pure async/promise functions:
async getStuff(state) {
const res = await fetch('/foo.json')
return { stuff: await res.json() }
},
// ... or just actions that call store.setState() later:
clearOutStuff(state) {
setTimeout(() => {
store.setState({ stuff: [] }) // clear 'stuff' after 1 second
}, 1000)
}
// Remember that the state passed to the action function could be stale after
// doing async work, so use getState() instead:
incrementAfterStuff(state) {
const res = await fetch('foo.json')
const resJson = await res.json()
// the variable 'state' above could now be old,
// better get a new one from the store
const upToDateState = store.getState()
return {
stuff: resJson,
count: upToDateState.count + resJson.length,
}
}
})
// Connecting a react/preact component to get current state and to bind actions
const App1 = connect('count', actions)(
({ count, increment, incrementBy }) => (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={() => incrementBy(10)}>Increment by 10</button>
</div>
)
)
// First argument to connect can also be a string, array or function while
// second argument can be an object or a function. Here we pass an array and
// a function.
const App2 = connect(['count', 'stuff'], actionFunctions)(
({ count, stuff, getStuff, clearOutStuff, incrementAfterStuff }) => (
<div>
<p>Count: {count}</p>
<p>Stuff:
<ul>{stuff.map(s => (
<li>{s.name}</li>
))}</ul>
</p>
<button onClick={getStuff}>Get some stuff!</button>
<button onClick={clearOutStuff}>Remove all stuff!</button>
<button onClick={incrementAfterStuff}>Get and count stuff!</button>
</div>
)
)
export const getApp1 = () => (
<Provider store={store}>
<App1 />
</Provider>
)
export const getApp2 = () => (
<Provider store={store}>
<App2 />
</Provider>
)
Debug
确保之前安装了 Redux devtools 扩展。
import createStore from 'unistore'
import devtools from 'unistore/devtools'
let initialState = { count: 0 };
let store = process.env.NODE_ENV === 'production' ? createStore(initialState) : devtools(createStore(initialState));
// ...
Examples
API
createStore
创建一个新商店,它是一个微型事件状态容器。
参数
state
Object Optional initial state (optional, default{}
)
示例
let store = createStore();
store.subscribe( state => console.log(state) );
store.setState({ a: 'b' }); // logs { a: 'b' }
store.setState({ c: 'd' }); // logs { a: 'b', c: 'd' }
返回 store
store
一个可观察的状态容器,从 createStore
action
创建给定操作函数的绑定副本。 绑定的返回函数调用 action() 并将结果保存回存储。 如果 action
的返回值是一个 Promise,解析后的值将被用作状态。
参数
action
Function An action of the formaction(state, ...args) -> stateUpdate
返回函数 boundAction ()
setState
将部分状态对象应用于当前状态,调用已注册的侦听器。
参数
update
Object An object with properties to be merged into stateoverwrite
Boolean Iftrue
, update will replace state instead of being merged into it (optional, defaultfalse
)
subscribe
注册一个侦听器函数,只要状态发生变化就会被调用。 返回一个 unsubscribe()
函数。
参数
listener
Function A function to call when state changes. Gets passed the new state.
返回函数取消订阅()
unsubscribe
移除一个之前注册的监听函数。
参数
listener
Function The callback previously passed tosubscribe()
that should be removed.
getState
检索当前状态对象。
返回 Object 状态
connect
将组件连接到商店。 将状态作为道具传递,重新呈现变化。
参数
mapStateToProps
(Function | Array | String) A function mapping of store state to prop values, or an array/CSV of properties to map.actions
(Function | Object)? Action functions (pure state mappings), or a factory returning them. Every action function gets current state as the first parameter and any other params next
示例
const Foo = connect('foo,bar')( ({ foo, bar }) => <div /> )
const actions = { someAction }
const Foo = connect('foo,bar', actions)( ({ foo, bar, someAction }) => <div /> )
返回 组件 ConnectedComponent
Provider
扩展组件
提供者公开商店(作为 props.store) 到上下文中。
通常,整个应用程序都包含在根部的单个
中。
参数
props
Objectprops.store
Store A {Store} instance to expose via context.
Reporting Issues
发现问题? 想要一个新功能? 首先,查看您的问题或想法是否已被报告。 如果没有,只需打开一个新的清晰且描述性的问题。
License
unistore
A tiny 350b centralized state container with component bindings for Preact & React.
- Small footprint complements Preact nicely (unistore + unistore/preact is ~650b)
- Familiar names and ideas from Redux-like libraries
- Useful data selectors to extract properties from state
- Portable actions can be moved into a common place and imported
- Functional actions are just reducers
- NEW: seamlessly run Unistore in a worker via Stockroom
Table of Contents
Install
This project uses node and npm. Go check them out if you don't have them locally installed.
npm install --save unistore
Then with a module bundler like webpack or rollup, use as you would anything else:
// The store:
import createStore from 'unistore'
// Preact integration
import { Provider, connect } from 'unistore/preact'
// React integration
import { Provider, connect } from 'unistore/react'
Alternatively, you can import the "full" build for each, which includes both createStore
and the integration for your library of choice:
import { createStore, Provider, connect } from 'unistore/full/preact'
The UMD build is also available on unpkg:
<!-- just unistore(): -->
<script src="https://unpkg.com/unistore/dist/unistore.umd.js"></script>
<!-- for preact -->
<script src="https://unpkg.com/unistore/full/preact.umd.js"></script>
<!-- for react -->
<script src="https://unpkg.com/unistore/full/react.umd.js"></script>
You can find the library on window.unistore
.
Usage
import createStore from 'unistore'
import { Provider, connect } from 'unistore/preact'
let store = createStore({ count: 0, stuff: [] })
let actions = {
// Actions can just return a state update:
increment(state) {
// The returned object will be merged into the current state
return { count: state.count+1 }
},
// The above example as an Arrow Function:
increment2: ({ count }) => ({ count: count+1 }),
// Actions receive current state as first parameter and any other params next
// See the "Increment by 10"-button below
incrementBy: ({ count }, incrementAmount) => {
return { count: count+incrementAmount }
},
}
// If actions is a function, it gets passed the store:
let actionFunctions = store => ({
// Async actions can be pure async/promise functions:
async getStuff(state) {
const res = await fetch('/foo.json')
return { stuff: await res.json() }
},
// ... or just actions that call store.setState() later:
clearOutStuff(state) {
setTimeout(() => {
store.setState({ stuff: [] }) // clear 'stuff' after 1 second
}, 1000)
}
// Remember that the state passed to the action function could be stale after
// doing async work, so use getState() instead:
incrementAfterStuff(state) {
const res = await fetch('foo.json')
const resJson = await res.json()
// the variable 'state' above could now be old,
// better get a new one from the store
const upToDateState = store.getState()
return {
stuff: resJson,
count: upToDateState.count + resJson.length,
}
}
})
// Connecting a react/preact component to get current state and to bind actions
const App1 = connect('count', actions)(
({ count, increment, incrementBy }) => (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={() => incrementBy(10)}>Increment by 10</button>
</div>
)
)
// First argument to connect can also be a string, array or function while
// second argument can be an object or a function. Here we pass an array and
// a function.
const App2 = connect(['count', 'stuff'], actionFunctions)(
({ count, stuff, getStuff, clearOutStuff, incrementAfterStuff }) => (
<div>
<p>Count: {count}</p>
<p>Stuff:
<ul>{stuff.map(s => (
<li>{s.name}</li>
))}</ul>
</p>
<button onClick={getStuff}>Get some stuff!</button>
<button onClick={clearOutStuff}>Remove all stuff!</button>
<button onClick={incrementAfterStuff}>Get and count stuff!</button>
</div>
)
)
export const getApp1 = () => (
<Provider store={store}>
<App1 />
</Provider>
)
export const getApp2 = () => (
<Provider store={store}>
<App2 />
</Provider>
)
Debug
Make sure to have Redux devtools extension previously installed.
import createStore from 'unistore'
import devtools from 'unistore/devtools'
let initialState = { count: 0 };
let store = process.env.NODE_ENV === 'production' ? createStore(initialState) : devtools(createStore(initialState));
// ...
Examples
API
createStore
Creates a new store, which is a tiny evented state container.
Parameters
state
Object Optional initial state (optional, default{}
)
Examples
let store = createStore();
store.subscribe( state => console.log(state) );
store.setState({ a: 'b' }); // logs { a: 'b' }
store.setState({ c: 'd' }); // logs { a: 'b', c: 'd' }
Returns store
store
An observable state container, returned from createStore
action
Create a bound copy of the given action function. The bound returned function invokes action() and persists the result back to the store. If the return value of action
is a Promise, the resolved value will be used as state.
Parameters
action
Function An action of the formaction(state, ...args) -> stateUpdate
Returns Function boundAction()
setState
Apply a partial state object to the current state, invoking registered listeners.
Parameters
update
Object An object with properties to be merged into stateoverwrite
Boolean Iftrue
, update will replace state instead of being merged into it (optional, defaultfalse
)
subscribe
Register a listener function to be called whenever state is changed. Returns an unsubscribe()
function.
Parameters
listener
Function A function to call when state changes. Gets passed the new state.
Returns Function unsubscribe()
unsubscribe
Remove a previously-registered listener function.
Parameters
listener
Function The callback previously passed tosubscribe()
that should be removed.
getState
Retrieve the current state object.
Returns Object state
connect
Wire a component up to the store. Passes state as props, re-renders on change.
Parameters
mapStateToProps
(Function | Array | String) A function mapping of store state to prop values, or an array/CSV of properties to map.actions
(Function | Object)? Action functions (pure state mappings), or a factory returning them. Every action function gets current state as the first parameter and any other params next
Examples
const Foo = connect('foo,bar')( ({ foo, bar }) => <div /> )
const actions = { someAction }
const Foo = connect('foo,bar', actions)( ({ foo, bar, someAction }) => <div /> )
Returns Component ConnectedComponent
Provider
Extends Component
Provider exposes a store (passed as props.store
) into context.
Generally, an entire application is wrapped in a single <Provider>
at the root.
Parameters
props
Objectprops.store
Store A {Store} instance to expose via context.
Reporting Issues
Found a problem? Want a new feature? First of all, see if your issue or idea has already been reported. If not, just open a new clear and descriptive issue.