Hooks
怎么使用hooks,将service注入到react组件中:
简单用法
const app = () => {
const [state, actions] = useService(DemoService)
// state.count
// actions.add, actions.reset, actions.setCount ...
return <div>{state.count}</div>
}
// 等价于:
const app2 = () => {
// 手动使用container获取DemoService的实例,切忌不可直接new DemoService
const demoService = container.resolveInScope(DemoService)
const [state, actions] = useServiceInstance(demoService)
// ...
}
使用Selector
上述例子中,当state变化的时候,组件也会重新渲染,但是有的时候,全部重新是一种浪费,因此这里也实现了一个类型于react-redux里面的mapStateToProps
的筛选函数:
const app =() => {
// 只有当count变化的时候,
const [count, actions] = useService(DemoService, state => state.count)
// count
// actions.add, actions.reset, actions.setCount ...
return <div>{count}</div>
}
// 等价于
const app2 = () => {
// 手动使用container获取DemoService的实例,切忌不可直接new DemoService
const demoService = container.resolveInScope(DemoService)
const [count, actions] = useServiceInstance(demoService, state => state.count)
// ...
}
特别的,当你完全不想让state的变化触发重渲染的时候可以这样:
const [,actions] = useService(DemoService, () => undefined)
// 等价于:
const actions = useService(DemoService)
// 等价于:
const [,actions] = useServiceInstance(demoService, () => undefined)
// 等价于:
const actions = useServiceInstance(demoService)
限定Scope
默认注入都是单例(Singleton),可以手动修改:
const app =() => {
const [count] = useService(DemoService, state => state.count,{scope: Transient})
const [state, actions] = useService(DemoService, {scope: Transient})
useEffect(() => actions.add(1), [])
// count
// actions.add, actions.reset, actions.setCount ...
return <div> count1: {count}, count2: {state.count} </div>
// count1: 0, count2: 1
}
Last updated
Was this helpful?