import storact from 'storact'
const {
useDispatch,
useStoreState,
Provider,
} = storact({
initialState,
middlewares,
effects,
namespace,
})
export { useDispatch, useStoreState, Provider }
{
members: [{
name: 'Yu',
age: '22',
}, {
name: 'Han',
age: '20',
}]
}
// useStoreState(['members', 0, 'name']) => 'Yu'
// useStoreState(['members', 1]) => { name: 'Han', age: '20' }
// useStoreState(['members']) => [{name: 'Yu', age: '22'}, {name: 'Han', age: '20'}]
// useStoreState([]) 或者 useStoreState() => 直接返回整个状态
这里需要注意,即使是在同一个组件内,分别调用useStoreState返回的状态是不关联的,也就是说useStoreState返回的是一个“当前状态的快照“,这样的话也同时保证了store的不可变性,例如:
const members = useStoreState(['members'])
const member1 = useStoreState(['members', 1])
members[1].name = 'Other'
console.log(members[1].name) // 'Other'
console.log(member1.name) // 'Han'
import { useDispatch, useStoreState, Provider } from './myStore'
function App() {
const members = useStoreState(['members'])
return (
<div>
{members.map(({ name, age }) => <p>{name}: {age}</p>)}
</div>
)
}