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.

本文标签: javascriptHow do I create a factory function to return a Mise store in React with reactmiseStack Overflow