无法使用setstate钩子复制数组 [英] Unable to copy array using setstate hook

查看:55
本文介绍了无法使用setstate钩子复制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我尝试更新未更新的挂钩时,我都会使用axios从后端获取数据.数据是从中提取数据并尝试设置元素的JSON.听起来很傻,但是有人可以告诉我什么是依赖数组吗?

I am fetching data from backend using axios whenever I am trying to update hooks it is not updating. The data is JSON from where I am extracting data and trying to set element. It might sound silly but can somebody tell me what is dependent array?

我不断得到这个
第18行:React Hook useEffect缺少依赖项:'elements'.要么包含它,要么删除依赖项数组react-hooks/exhaustive-deps

这是代码

import React, { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';

function App() {
  const [elements, setElements] = useState([]);

  useEffect(() => {
    const res = async () => {
      const result = await axios.get('/data');
      const data = result.data;
      console.log(data);
      setElements(elements => [...elements, data]);
      console.log(elements);
    };
    res();
  }, []);
 console.log(elements.map(element => console.log(element)));
  return <div className='App'>Hello</div>;
}

export default App;

推荐答案

只是 console.log 在您的效果之外.您已经在使用 useState

Just console.log outside your effect. You're already using the updater version of useState

 setElements(elements => [...elements, data])

缺少的依赖性警告来自 console.log(elements)

The missing dependecy warning is coming from console.log(elements)

import React, { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';

function App() {
  const [elements, setElements] = useState([]);

  useEffect(() => {
    const res = async () => {
      const result = await axios.get('/data');
      const data = result.data;
      console.log(data);
      setElements(elements => [...elements, data]);
    };
    res();
  }, []);

  console.log(elements);

  return <div className='App'>Hello</div>;
}

export default App;

这篇关于无法使用setstate钩子复制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆