// ......
export { useDispatch, useStoreState, Provider }
useDispatch是在组件中引入dispatch的方法,使用方法如下
import React, { useCallback } from 'react'
import { useDispatch, useStoreState, Provider } from './myStore'
function App() {
const members = useStoreState(['members'])
const dispatch = useDispatch()
const handleClick = useCallback(() => {
// 添加一个成员
dispatch.push(['member'], { name: 'Lv', age: '33' })
})
return (
<div>
{members.map(({ name, age }) => <p>{name}: {age}</p>)}
<button onClick={handleClick}>add a member</button>
</div>
)
}
storact采取固化reducer的操作,同时去掉声明式的action,改成属性方法调用
dispatch.XXX(path, otherParams)
// 例如当前的状态如下
{
team: 'Cloud-Internet',
members: [{
name: 'Yu',
age: '22',
}, {
name: 'Han',
age: '20',
}]
}
path是需要修改的状态的"访问路径",如果不指定或者传空数组,则是针对整个store进行修改,XXX就是固化的reducer类型,有以下几种
1. update
更新的操作,使用新的数据覆盖当前的状态
dispatch.update(['member'], [{ name: 'Shi', age: '41' }])
// 修改之后的状态
{
team: 'Cloud-Internet',
members: [{
name: 'Shi',
age: '41',
}]
}
2. delete
删除状态
dispatch.delete(['member', '1'])
// 修改之后的状态
{
team: 'Cloud-Internet',
members: [{
name: 'Yu',
age: '22',
}]
}
3. clear
清空状态,对于对象,则会变成空对象,对于数组,则会变成空数组
dispatch.clear(['member'])
// 修改之后的状态
{
team: 'Cloud-Internet',
members: []
}
4. merge
针对对象,进行浅层合并状态
dispatch.merge([], { members: [{ name: 'Zhong', 'age': '18' }] })
// 修改之后的状态
{
team: 'Cloud-Internet',
members: [{
name: 'Zhong',
age: '18',
}]
}