简体   繁体   English

Map function 全局反应上下文增量 state

[英]Map function increment on global react context state

I need some help with incrementing a value through map function while using React's context API.在使用 React 的上下文 API 时,我需要一些帮助来增加一个值。 Here is an example to better understand: Let's say I have items:这是一个更好理解的示例:假设我有物品:

const [items, setItems] = useContext(ItemsContext)

These items are JSON objects inside an array.这些项目是数组中的 JSON 对象。 And then I want to return each item's properties in a list but some of them modified - for example, the item has quantity and I want to increment/decrement it on click.然后我想在列表中返回每个项目的属性,但其中一些已修改 - 例如,该项目有数量,我想在点击时增加/减少它。 How do I achieve this individually for every item?我如何为每个项目单独实现这一目标?

I tried making a local state for the quantities:我尝试为数量制作本地 state:

const [quantity, setQuantity] = useState([])

,so I have all the quantities of all elements but it got me nowhere. ,所以我拥有所有元素的所有数量,但它让我无处可去。

The thing I am trying to accomplish is similar to this:我想要完成的事情与此类似:

<div>
<ul>
{
 items.map(item => (
 <li>
     <p>item.name</p>
     <p>item.quantity</p>
     <button onClick={incQuantity}>  </button>
 </li>
 }
</ul>
</div>

Edit:编辑:

const [idCounter, setIdCounter] = useState(0)

I use props.我用道具。 here because this is another component.在这里,因为这是另一个组件。

const addItem = () => {
        if (quantity > 0) {
            setIdCounter(idCounter + 1)
            setItems(prevItems => [...prevItems, {id: idCounter, name: props.name, price: props.price, quantity: quantity }])
        }
    }

And I implemented the handler quite the same:我实现的处理程序完全相同:

const quantityHandler = (id, diff) => {
    setItems(items.map((item) => 
        item.id === id ? {...item, quantity: item.quantity + diff} : item
    ))
}

And here is the list itself:这是列表本身:

<div>
<ul>
{
 items.map(item => (
 <li>
     <p>item.name</p>
     <p>item.quantity</p>
     <button onClick={() => quantityHandler(item.id, 1)}>  </button>
     <button onClick={() => quantityHandler(item.id, -1)}>  </button>
 </li>
 }
</ul>
</div>

Here is working example and I will explain it a little: in App we make MyContext and state with hook, then we provide state and function to update state to Context provider as value . Here is working example and I will explain it a little: in App we make MyContext and state with hook, then we provide state and function to update state to Context provider as value . Then in any place inside Provider we have access to that state and setter.然后在 Provider 内部的任何地方,我们都可以访问 state 和 setter。 We render items and we can update them using hook setter from Context.我们渲染项目,我们可以使用来自 Context 的钩子设置器更新它们。

import React, { useState, useContext } from "react";

const MyContext = React.createContext(null);

const initialState = [
  { id: 1, quantity: 1 },
  { id: 2, quantity: 2 },
  { id: 3, quantity: 3 },
  { id: 4, quantity: 4 },
];

const DeepNestedComponent = () => {
  const [stateFromContext, setStateFromContext] = useContext(MyContext);
  // MyContext should be imported

  const buttonHandler = (id, diff) => {
    setStateFromContext(
      stateFromContext.map((item) =>
        item.id === id ? { ...item, quantity: item.quantity + diff } : item
      )
    );
  };

  return (
    <div>
      {stateFromContext.map(({ id, quantity }) => (
        <div key={id}>
          {quantity}
          <button onClick={() => buttonHandler(id, 1)}> + </button>
          <button onClick={() => buttonHandler(id, -1)}> - </button>
        </div>
      ))}
    </div>
  );
};

const App = () => {
  const [contextState, setContextState] = useState(initialState);

  return (
    <MyContext.Provider value={[contextState, setContextState]}>
      <DeepNestedComponent />
    </MyContext.Provider>
  );
};

export default App;

Like it if its is working )喜欢它,如果它正在工作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM