Effect
初始化时需要定义好effects,是一个函数集合
import storact from 'storact'
const {
useDispatch,
useStoreState,
Provider,
} = storact({
initialState,
middlewares,
effects, // effect集合 - optional
namespace,
})
export { useDispatch, useStoreState, Provider }
具体一个effect的格式如下
({ getState, dispatch }) => async () => {}
// getState同useStoreState(参考 "使用/创建store")
// dispatch不仅可以调用基础的action,还可以调用其他effect
具体使用
例如当前状态如下
{
total: 2,
members: [{
name: 'Yu',
age: '22',
}, {
name: 'Han',
age: '20',
}]
}
定义一个effect
// 这里需要加入一个member,并且把当前的total加一
const effects = {
addMember: ({ getState, dispatch }) => async (name, age) => {
// 获取当前状态中的total
const currentTotal = getState(['total'])
await dispatch.push(['member'], {
name,
age,
})
await dispatch.merge([], {
total: currentTotal + 1,
})
}
}
// 然后执行effect
dispatch.addMember('Zhong', 18)
// 之后状态变为
{
total: 3,
members: [{
name: 'Yu',
age: '22',
}, {
name: 'Han',
age: '20',
}, {
name: 'Zhong',
age: 18,
}]
}
再定义一个effect
const effects = {
// ............
// addMember同上
// ............
// 这里需要一次加入两个member,并保持total的逻辑
addMemberTwice: ({ dispatch }) => async (name1, age1, name2, age2) => {
await dispatch.addMember(name1, age1)
await dispatch.addMember(name2, age2)
}
}
// 然后执行effect
dispatch.addMemberTwice('Zhong', 18, 'Zhao', 30)
// 之后状态变为
{
total: 3,
members: [{
name: 'Yu',
age: '22',
}, {
name: 'Han',
age: '20',
}, {
name: 'Zhong',
age: 18,
}, {
name: 'Zhao',
age: 30,
}]
}
Last updated
Was this helpful?