简体   繁体   English

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

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

In the backend I am processing the data and then sending it to React through JSON.在后端,我正在处理数据,然后通过 JSON 将其发送到 React。 Here is the code.这是代码。

  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);

The backend I showed here is not the same as it is.我在这里展示的后端与它不一样。 I just showed it as an example.我只是把它作为一个例子来展示。 I had to use res.write and res.end because I had to collect data for different if conditions.我不得不使用 res.write 和 res.end 因为我必须为不同的 if 条件收集数据。

Below here is the code in react where I am getting this data through Axios.下面是我通过 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 Chrome 开发者控制台图片

Please tell me how to solve this with React Hooks.请告诉我如何使用 React Hooks 解决这个问题。 I think it has to be done with mapping but i don't how.我认为必须通过映射来完成,但我不知道。

To solve this with hooks you can fetch data when the component loads with useEffect hook and store it inside useState hook.要使用钩子解决这个问题,您可以在组件加载时使用 useEffect 钩子获取数据并将其存储在 useState 钩子中。

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

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

  const data3 = data.length

As @Tobias Geiselmann said axios.get() returns a promise, and you're assigning the length of the promise.正如@Tobias Geiselmann 所说, axios.get()返回 promise,并且您正在分配 promise 的长度。

If you return a value from .then() , the next then() is called with that value.如果您从.then()返回一个值,则使用该值调用下一个 then()。

After looking at your screenshot.看了你的截图后。 It looks like you're trying to access the length property from the data return by your API.看起来您正试图从 API 返回的数据中访问长度属性。 I would recommend structuring your API response like so我建议像这样构建您的 API 响应

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

By doing so you'll be to access the length with:通过这样做,您将通过以下方式访问长度:

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

Try this尝试这个

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

another example:另一个例子:

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

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

example with async/await async/await的示例

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

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

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

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