REACT HOOKS - 将 JSON 数据(从 API 通过 Axios)传递到 const

REACT HOOKS - Passing JSON data (From API through Axios) into const

在后台我处理数据然后通过JSON发送给React。这是代码。

  res.setHeader('Content-Type', 'application/json');
  var obj = {field: current, fieldCnt: cnt }
  var obj2 = JSON.stringify(obj)
  res.write(obj2);
  var obj3 = {length: currentcnt, field2: current, fieldCnt2: cnt }
  var obj4 = JSON.stringify(obj3)
  res.end(obj4);

我这里展示的后端和实际的不一样。我只是举个例子。我必须使用 res.write 和 res.end,因为我必须针对不同的 if 条件收集数据。

下面是我通过 Axios 获取这些数据的反应代码。

var data2 =  axios.get('http://localhost:5000/get').then(res => {
   console.log(res.data)      //Check the Attached Chrome Developers console image.
   return res.data
});

const data3 = data2.length   //This isn't working (length can be seen the console image last line "length" : 18)

Chrome Developers console image

请告诉我如何使用 React Hooks 解决这个问题。我认为它必须通过映射来完成,但我不知道如何。

要使用挂钩解决此问题,您可以在使用 useEffect 挂钩加载组件时获取数据并将其存储在 useState 挂钩中。

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

  useEffect(() => {
    axios.get('http://localhost:5000/get').then(res => setData(res.data))
  }, [])

  const data3 = data.length

正如@Tobias Geiselmann 所说,axios.get() return 是一个承诺,您正在分配承诺的长度。

如果您 return 来自 .then() 的值,则使用该值调用下一个 then()。

看了你的截图。看起来您正在尝试通过 API 从数据 return 访问长度 属性。我建议像这样 API 构建你的响应

{
  count: 18,
  results: [
    { key: 'val' },
    { key: 'val' },
    { key: 'val' },
  ]
}

通过这样做,您将可以通过以下方式访问长度:

res.data.count // will have the count
res.data.results // will have all the results

试试这个

axios.get('http://localhost:5000/get').then((res) => {
   console.log(res.data.length); // will print the length
});

另一个例子:

const data2 = axios.get('http://localhost:5000/get')
  .then((data) => {
    return data;
  });

data2.then(data => {
  console.log(data.length) // will print the length
})

示例 async/await

const myFunc = async () => {
  const { data } = await axios.get('http://localhost:5000/get');

  console.log(data.length); // will print the length
};