将存储对象重置为solidj中的默认值
您如何在 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/>
)
}
添加项目并按预期的是增加其数量。 当我:
- 添加一个项目。
- 增加其数量
- 项目
清除我希望该州空白的 。但是,如果我在列表中添加了与第一个属性相同的属性的项目,则将其显示为旧值。
我不知道为什么。我在做什么不对?
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:
- Add an item.
- Increment its quantity
- 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法正确使用商店API。例如,项目路径为您提供项目,您应该先获得该项目,而不是通过设置器进行更新:
这是您可以正确执行的方法:
这是您可以做到的。我没有揭露商店,而是商品。取决于你。
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:
Here is how you can do it correctly:
Here is how you can do it. I did not expose store but items. It is up to you.
您无法正确使用商店。 Check this live example here
You are not using the store correctly. Check this live example here