无法使用 setstate 挂钩复制数组

IT技术 javascript reactjs react-hooks
2021-05-24 18:22:44

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

我一直收到
第 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;
3个回答

console.log在您的effect. 您已经在使用的updater版本useState

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

缺少依赖警告来自 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;

Missing dependency警告是因为你console.log(elements)在useEffect里面使用并且您的元素日志未显示最新结果,因为状态尚未更改(尚未)

只需添加一个useEffect以跟踪元素更改,如下所示。

 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();
  }, []);

  useEffect(() => console.log(elements), [elements])

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

export default App;

回答你的问题;

依赖数组是他们让 React 知道在这种情况下何时应该触发 useEffect。因此,我添加的 useEffect 仅在其依赖项elements更改时触发

在您的情况下,您将数组数据放在元素内,setElements(elements => [...elements, data]);因此它将是数组内的数组。试试下面的:

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, data]);
    };
    res();
  }, []);

  useEffect(() => console.log(elements), [elements])

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

export default App;