简体   繁体   English

React 组件渲染两次(useEffect 运行两次)

[英]React component renderes twice (useeffect runs twice)

Hi i'm new to react js and i was wondering why my component is rendering twice(useeffect runs twice).嗨,我是反应 js 的新手,我想知道为什么我的组件渲染两次(useeffect 运行两次)。 I tried removing strict mode and it renders only once but even then i don't understand why count is shown as 01 instead of just only 1. if i add the event handler the component breaks and i get that newarray[id][1]-1 is undefined (the function runs even if i don't click - or +)我尝试删除严格模式,它只呈现一次,但即便如此我也不明白为什么计数显示为 01 而不仅仅是 1。如果我添加事件处理程序,组件会中断并且我得到那个 newarray[id][1] -1 未定义(即使我不单击 - 或 +,function 也会运行)

import React, { useEffect, useState } from "react";
import { useOutletContext } from "react-router-dom";




function ShoppingCart(prop) {

  const [productstobuy, setProducts] = useState([]);
  const [count, setCount] = useState([0])
  console.log(productstobuy)
/*
   const handlePlusMinus = (sign,id) => {
    console.log("i'm in")
     const newarray = [...productstobuy]
     console.log(newarray)
     if (sign === "+") {
       newarray[id][1] = newarray[id][1]+1
     } else if ((newarray[id][1]-1) >= 1) {
      newarray[id][1] = newarray[id][1]+1
     }
     setProducts(newarray);
     
    }
 */



  const allItems = useOutletContext()

  useEffect(() => {
    setCount(count + 1)
    console.log("called")
    let toadd = allItems.filter((elem, index) => { return index === prop.index })
    console.log(toadd);
    let productexsist = productstobuy.filter((elem) => { return elem[0] === toadd })
    console.log(productexsist.length)


    if (!productexsist.length) {
      console.log([(allItems.filter((elem, index) => { return index === prop.index }))[0], 1])
      setProducts(oldArray => [...oldArray, [toadd[0], 1]]);
      console.log(productstobuy)

    } else {
      console.log("wrong")
    }

  }, [prop.index])







  return (
    <div>
      {count}
      {console.log(productstobuy)}
      {productstobuy.length > 0 ? productstobuy.map((product) => {
        console.log(product[1])
        return (<div className="product" id={prop.index}>{product[0]}<div><button id={prop.index} /*onClick={handlePlusMinus("-",prop.index)}*/>-</button><input type="number" value={product[1]} /><button id={prop.index} /*onClick={handlePlusMinus("-",prop.index)}*/>+</button></div></div>)


      }) : null}
    </div>




  );




}


export { ShoppingCart }



why count is shown as 01 instead of just only 1为什么 count 显示为 01 而不仅仅是 1

It's because of this line const [count, setCount] = useState([0]) .这是因为这条线const [count, setCount] = useState([0]) count should be initialised as a number instead of an array. count 应该被初始化为一个数字而不是一个数组。 What actually happened in the useEffect was setCount([0]+1) instead of the intended setCount(0+1) useEffect 中实际发生的是setCount([0]+1)而不是预期的setCount(0+1)

the function runs even if i don't click - or +即使我不点击,function 也会运行 - 或 +

Instead of putting onClick={handlePlusMinus("-",prop.index)} , try onClick={() => handlePlusMinus("-",prop.index)} instead.不要放置onClick={handlePlusMinus("-",prop.index)} ,而是尝试onClick={() => handlePlusMinus("-",prop.index)} this would ensure that the handlePlusMinus function is only called when the element is clicked.这将确保仅在单击元素时才调用 handlePlusMinus function。 Elaboration here: React onClick function fires on render详细说明: React onClick function 在渲染时触发

It renders twice because of the Strict Mode.由于严格模式,它会渲染两次。
https://reactjs.org/docs/strict-mode.html https://reactjs.org/docs/strict-mode.html

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

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