javascript 当item被插入到React js Array状态中时,数据持续重复

u3r8eeie  于 2023-06-20  发布在  Java
关注(0)|答案(2)|浏览(112)

当item被插入到React js Array状态时,数据正在被复制,

console.log(newData)

输出单个对象,而

console.log(data)

输出连续重复

console.log(newData)

我该怎么修

const [data, setData] = useState([])

    const addData = (newData) => {
       
        console.log(newData)
        setData(prevData => [...prevData, newData]);
        console.log(data)
        
    };

    useEffect(() => {
          axios
            .get(`http://localhost:3000/api/products/${pid}`)
            .then((res) => {
              addData(res.data); // Update the state directly with the response data
            })
            .catch((err) => {
              console.log(err);
            });
       
    });
n3ipq98p

n3ipq98p1#

useEffect(()=> {
   axios
            .get(`http://localhost:3000/api/products/${pid}`)
            .then((res) => {
              addData(res.data); // Update the state directly with the response data
            })
            .catch((err) => {
              console.log(err);
            });
}, [data]) // Add the [data] (The dependency array) to say that we want this renders only when this var changes
gc0ot86w

gc0ot86w2#

const [data, setData] = useState([])
    const addData = (newData) => {
        console.log(newData)
        setData(prevData => [...prevData, newData]);
        console.log(data)
    };

    useEffect(() => {
      // even if useEffect is called again, you will only execute code, if your state array is empty
      if(data.length === 0){
        axios
        .get(`http://localhost:3000/api/products/${pid}`)
        .then((res) => {
           cosole.log("res.data", res.data);
          // make sure res.data is an array
          addData(res.data); // Update the state directly with the response data
        })
        .catch((err) => {
          // always use console.error() to print the errors
          console.error(err);
        });
      }
    }, []); 
//  add your dependency here, I kept it empty, 
// because I assume, you want to add the data in the first render only

相关问题