admin管理员组文章数量:1291215
I am new to Mise stores in React.
I am creating a single store like this:
// store.js
import { defineStore } from "react-mise"
export const useStore = defineStore('counter', {
state: counter,
actions: {
increment () {
this.counter++
},
decrement () {
this.counter--
},
set (n) {
this.counter = n
},
reset () {
this.counter = 0
}
}
})
export function counter (n = 0) {
return {
counter: n
}
}
// MiseStore.jsx
import { useStore } from './store'
export default function Mise () {
const [store] = useStore()
<div>{store.counter}</div>
}
This works fine - the counter changes as the increment, decrement, set and reset functions are called and React updates appropriately.
However, I need to create a new instance for multiple components that do not share state.
I would like to use the factory function pattern to do it, like this:
// store.js
import { defineStore } from "react-mise"
export function useStoreFactory (id) {
return defineStore(id, {
state: counter,
actions: {
increment () {
console.log('#increment', this.counter)
this.counter++
},
decrement () {
console.log('#decrement', this.counter)
this.counter--
},
set (n) {
console.log('#set', this.counter)
this.counter = n
},
reset () {
console.log('#reset', this.counter)
this.counter = 0
}
}
})
}
// MiseStore.jsx
import { useStoreFactory } from './store'
export default function Mise () {
const useStore = useStoreFactory('counter-2')
const [store] = useStore()
<div>{store.counter}</div>
<div onClick={() => store.increment()}>increment</div>
}
... but when I do that, the store doesn't work as expected - the increment method is called but the value doesn't update in React.
版权声明:本文标题:javascript - How do I create a factory function to return a Mise store in React with react-mise? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741511083a2382610.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论