【问题标题】:React UseState()反应使用状态()
【发布时间】:2022-01-05 12:16:19
【问题描述】:

每当有人单击按钮(增量/减量)时,我都会尝试更改产品数量的状态。但不知何故,它并没有增加这里的数量。 当我单击增量按钮时,它会更改第一项的数量。当我单击第二个项目增量按钮时,它会重置第一个项目的数量并更改第二个项目。 [1]:https://i.stack.imgur.com/fifeQ.png

这是我的code

**App.js**

function App() {

let [productList, setProductList] = useState([]);

productList = [
{
      id: 0,
      prodName: "iPhone X",
      type: "Mobile",
      price: "80000",
      quantity: 0,
},
{
      id: 1,
      prodName: "iPhone 11",
      type: "Mobile",
      price: "120000",
      quantity: 0,
},
{
      id: 2,
      prodName: "iPhone 12",
      type: "Mobile",
      price: "180000",
      quantity: 0,

}];

const incrementQuantity = (index) => {
    let newProductList = [...productList];
    newProductList[index].quantity++;
    setProductList(newProductList);
    console.log(newProductList); 
}
return (
    <div className="App">
      
      <Header heading="Simple Cart project" />
      <Mediator list={productList} incrementQuantity={incrementQuantity} />
      {/* list is the property name which you are passing to different component */}
    </div>
  );
}

export default App;
    

**Mediator.js**
    
function Mediator(props) {
    return (
            props.list.map((product, index) => {

                return <ProductList productList={product} key={index} incrementQuantity = {props.incrementQuantity} index={index}/>
            })
    );
}
export default Mediator;
    
    
**ProductList.js**
    
function ProductList(props) {
    console.log("inside product list")
    console.log(props);

    return (
        <div className="row">
            <div className="col-5">
                <h2>{props.productList.prodName} </h2> <span className="price-column"><Chip label={props.productList.price} color="success" />₹ <br />
                </span> <br />
            </div>
            <div className="col-3">
                <ButtonGroup size="small" color="secondary" aria-label="small button group">
                    <Button className="btn-decrease">-</Button>
                   
                    <Box
                        component="div"
                        sx={{
                            display: 'inline',
                            p: 1,
                            m: 1,
                            bgcolor: 'background.paper',
}}
                    >
                        {props.productList.quantity}
                    </Box>

                    <Button className="btn-increase"
                        onClick={() => { props.incrementQuantity(props.index) }}

                    >+</Button>
                </ButtonGroup>
            </div>
            <div className="col-4">
                <span><h4>Total Cart Price: </h4>{props.productList.quantity * props.productList.price}</span>
            </div>
        </div>

    );
}

export default ProductList;

【问题讨论】:

    标签: javascript reactjs react-hooks use-state


    【解决方案1】:

    因为在每次渲染时,您要做的第一件事就是将保存状态的变量本地修改为硬编码的初始值列表。不要像那样改变状态。

    相反,将硬编码的初始值设置为 useState 挂钩的初始默认值:

    let [productList, setProductList] = useState([
    {
          id: 0,
          prodName: "iPhone X",
          type: "Mobile",
          price: "80000",
          quantity: 0,
    },
    {
          id: 1,
          prodName: "iPhone 11",
          type: "Mobile",
          price: "120000",
          quantity: 0,
    },
    {
          id: 2,
          prodName: "iPhone 12",
          type: "Mobile",
          price: "180000",
          quantity: 0,
    
    }]);
    

    永远不要直接修改或替换productList,只能使用setProductList来更新。

    【讨论】:

      【解决方案2】:

      David's answer is correct 但您的代码还有另一个问题是,如果您想修改 setProductList 以确保安全(例如不同的@ 987654325@ call) 已修改。

      function App() {
      
        const [productList, setProductList] = useState([
          {
            id: 0,
            prodName: "iPhone X",
            type: "Mobile",
            price: "80000",
            quantity: 0,
          },
          {
            id: 1,
            prodName: "iPhone 11",
            type: "Mobile",
            price: "120000",
            quantity: 0,
          },
          {
            id: 2,
            prodName: "iPhone 12",
            type: "Mobile",
            price: "180000",
            quantity: 0,
      
          }]);
      
        const incrementQuantity = (index) => {
          setProductList((prodList) => {
            prodList[index].quantity++;
            return prodList;
          });
        }
        
        ...
      }
      

      【讨论】:

      • 您不应该克隆prodList,然后在克隆的prodList 上增加数量,而不是直接改变状态?
      • 非常感谢@David,我也是 Joe。现在代码工作正常。 :) 我也同意 Sangeet Agarwal 的观点。我们应该先克隆 productList 而不是直接更改初始值!
      猜你喜欢
      • 2021-07-27
      • 2021-03-23
      • 1970-01-01
      • 2021-06-20
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 2021-03-30
      相关资源
      最近更新 更多