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
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)
// ...
}限定Scope
Last updated
Was this helpful?