将存储对象重置为solidj中的默认值

发布于 2025-02-01 02:39:37 字数 1218 浏览 3 评论 0原文

您如何在 solidjs 中完全重置商店中的价值,

我有类似的东西:

interface Item { id: number, price: number, quantity: number } 
​interface State { items: Array<Item> }

export const ItemsContext = createContext()

export const ContextProvider = (props: any) => { 
     const [state, setState] = createStore({items: []})
     
     const incrementItemQuantity = ({id}: Item) => {
         const index = state.items.findIndex(i => i.id === id)

         if(index !== -1) {
             const item = state.items[index] 
             setState("items", index, {quantity: item.quantity + 1})
         }
     }

     const clearItems  = () => {
       setState(produce(s => s.items = []))
     }

     const addItem = (item: Item) => {
       setState(produce(s => s.items.push(item))
     }
    
    const value = [state, { addItem, clearItems, incrementItemQuantity} ]
    return (
     <ItemsContext.Provider value={value} >
      { props.children }
     <ItemsContext.Provider/>
    )
    
}

添加项目并按预期的是增加其数量。 当我:

  1. 添加一个项目。
  2. 增加其数量
  3. 项目

清除我希望该州空白的 。但是,如果我在列表中添加了与第一个属性相同的属性的项目,则将其显示为旧值。

我不知道为什么。我在做什么不对?

How would you completely reset a value in a store in SolidJS

I have something akin to:

interface Item { id: number, price: number, quantity: number } 
​interface State { items: Array<Item> }

export const ItemsContext = createContext()

export const ContextProvider = (props: any) => { 
     const [state, setState] = createStore({items: []})
     
     const incrementItemQuantity = ({id}: Item) => {
         const index = state.items.findIndex(i => i.id === id)

         if(index !== -1) {
             const item = state.items[index] 
             setState("items", index, {quantity: item.quantity + 1})
         }
     }

     const clearItems  = () => {
       setState(produce(s => s.items = []))
     }

     const addItem = (item: Item) => {
       setState(produce(s => s.items.push(item))
     }
    
    const value = [state, { addItem, clearItems, incrementItemQuantity} ]
    return (
     <ItemsContext.Provider value={value} >
      { props.children }
     <ItemsContext.Provider/>
    )
    
}

Adding an item and incrementing its quantity works as expected.
When I:

  1. Add an item.
  2. Increment its quantity
  3. Clear the items

I expect the state to be blank. However, If I add an item with the same properties as the first to the list, it is displayed with the old values.

I can't figure out why. What am I not doing right ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

安人多梦 2025-02-08 02:39:37

您无法正确使用商店API。例如,项目路径为您提供项目,您应该先获得该项目,而不是通过设置器进行更新:

setState("items", index, {quantity: item.quantity + 1});

这是您可以正确执行的方法:

// Here path gives us the item
setState("items", index, item => ({...item, quantity: item.quantity + 1}));

// Here path gives us the property
setState('items', index, 'quantity', q => q + 1);

这是您可以做到的。我没有揭露商店,而是商品。取决于你。

// @refresh reload
import { createContext, JSX, useContext } from "solid-js";
import { createStore, produce } from 'solid-js/store';
import { render } from "solid-js/web";

interface Item { id: number, price: number, quantity: number }

interface Store {
  items: () => Array<Item>;
  add?: (item: Item) => void;
  increment?: (index: number) => void;
  clear?: () => void;
};

export const CartContext = createContext<Store>();

export const CartProvider = (props: { children: JSX.Element }) => {
  const [store, setStore] = createStore({ items: [{ id: 0, price: 10, quantity: 1 }] })

  const items = () => store.items;
  const add = (item: Item) => setStore('items', items => [...items, item]);
  const increment = (index: number) => setStore('items', index, 'quantity', q => q + 1);
  const clear = () => setStore('items', []);

  return (
    <CartContext.Provider value={{ items, add, increment, clear }}>
      {props.children}
    </CartContext.Provider>
  );
}

const Child = () => {
  const { items, add, increment, clear } = useContext(CartContext);
  return (
    <div>
      <ul>
        {items().map((item, index) => (
          <li>{JSON.stringify(item)} <button onclick={() => increment(index)}>inc</button></li>)
        )}
      </ul>
      <div>
        <button onClick={() => add({ id: items().length, price: 10, quantity: 1 })}>Add Item</button>
        {` `}
        <button onClick={() => clear()}>Clear Items</button>
      </div>
    </div>
  )
};

const App = () => {
  return (
    <CartProvider>
      <Child />
    </CartProvider>
  );
}

render(App, document.querySelector("#app"));

You are not using the store API correctly. For example, the item path gives you the item, you should get the item first, than update it through a setter:

setState("items", index, {quantity: item.quantity + 1});

Here is how you can do it correctly:

// Here path gives us the item
setState("items", index, item => ({...item, quantity: item.quantity + 1}));

// Here path gives us the property
setState('items', index, 'quantity', q => q + 1);

Here is how you can do it. I did not expose store but items. It is up to you.

// @refresh reload
import { createContext, JSX, useContext } from "solid-js";
import { createStore, produce } from 'solid-js/store';
import { render } from "solid-js/web";

interface Item { id: number, price: number, quantity: number }

interface Store {
  items: () => Array<Item>;
  add?: (item: Item) => void;
  increment?: (index: number) => void;
  clear?: () => void;
};

export const CartContext = createContext<Store>();

export const CartProvider = (props: { children: JSX.Element }) => {
  const [store, setStore] = createStore({ items: [{ id: 0, price: 10, quantity: 1 }] })

  const items = () => store.items;
  const add = (item: Item) => setStore('items', items => [...items, item]);
  const increment = (index: number) => setStore('items', index, 'quantity', q => q + 1);
  const clear = () => setStore('items', []);

  return (
    <CartContext.Provider value={{ items, add, increment, clear }}>
      {props.children}
    </CartContext.Provider>
  );
}

const Child = () => {
  const { items, add, increment, clear } = useContext(CartContext);
  return (
    <div>
      <ul>
        {items().map((item, index) => (
          <li>{JSON.stringify(item)} <button onclick={() => increment(index)}>inc</button></li>)
        )}
      </ul>
      <div>
        <button onClick={() => add({ id: items().length, price: 10, quantity: 1 })}>Add Item</button>
        {` `}
        <button onClick={() => clear()}>Clear Items</button>
      </div>
    </div>
  )
};

const App = () => {
  return (
    <CartProvider>
      <Child />
    </CartProvider>
  );
}

render(App, document.querySelector("#app"));
半葬歌 2025-02-08 02:39:37

您无法正确使用商店。 Check this live example here

import { render } from "solid-js/web";
import { createContext, useContext, For } from "solid-js";
import { createStore } from "solid-js/store";

export const CounterContext = createContext([{ items: [] }, {}]);
export function CounterProvider(props) {
  const [state, setState] = createStore({ items: props.items || []});
  const store = [
    state,
    {
      add: (val) => setState("items", (c) => [...c, val]),
      clear: () => setState("items", () => []),
    },
  ];

  return (
    <CounterContext.Provider value={store}>
      {props.children}
    </CounterContext.Provider>
  );
}

const Counter = () => {
  const [state, { add,clear }] = useContext(CounterContext);
  return <>
    <For each={state.items}>
      {(i) => (<h1>{i}</h1>)}
    </For>
    <button  onClick={() => add(state.items.length + 1)}>Add </button>
    <button  onClick={clear}>Clear </button>
    </>
};

const App = () => (
  <CounterProvider>
    <Counter />
  </CounterProvider>
);
render(() => <App />, document.getElementById("app")!);

You are not using the store correctly. Check this live example here

import { render } from "solid-js/web";
import { createContext, useContext, For } from "solid-js";
import { createStore } from "solid-js/store";

export const CounterContext = createContext([{ items: [] }, {}]);
export function CounterProvider(props) {
  const [state, setState] = createStore({ items: props.items || []});
  const store = [
    state,
    {
      add: (val) => setState("items", (c) => [...c, val]),
      clear: () => setState("items", () => []),
    },
  ];

  return (
    <CounterContext.Provider value={store}>
      {props.children}
    </CounterContext.Provider>
  );
}

const Counter = () => {
  const [state, { add,clear }] = useContext(CounterContext);
  return <>
    <For each={state.items}>
      {(i) => (<h1>{i}</h1>)}
    </For>
    <button  onClick={() => add(state.items.length + 1)}>Add </button>
    <button  onClick={clear}>Clear </button>
    </>
};

const App = () => (
  <CounterProvider>
    <Counter />
  </CounterProvider>
);
render(() => <App />, document.getElementById("app")!);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文