需要在Next.js中获取数据后显示网页。

huangapple go评论65阅读模式
英文:

need to make web page dispaly after fething the data in Next.js

问题

I'm using Next.js, where I'm new to Next.js; I have some knowledge in JavaScript.
I have written some code to get the API of my JSON file (which is my data that needs to be displayed on the /blogs webpage):

import React from 'react'

const blogs = () => {
 var element
 (async () => {

  var data = await fetch("http://localhost:3000/api")
  data = await data.json();
  console.log(data);
  console.log(data.length)
  for (let index = 0; index < data.length; index++) {
     element = data[index];
    // document.getElementById(tilte).innerHTML+=element["title"]
    console.log(element["title"])
  }
})()

// Rest of your code...

export default blogs

In this above code, I have written some code to fetch data from an API, but the above-commented code (document.getElementById(tilte).innerHTML+=element["title"]) is not working, and I'm getting an error as "Cannot read properties of null (reading 'innerHTML')". I wanted to print this on my web page, so I tried to print it in the return function, which also did not work.

return (
    <>
    <div><h1>
      Welcome to my blogs
    </h1></div>
  
    <div id="tilte">
          {console.log(element["title"])}
    </div>
    </>
  )

In this code, I tried to console.log my element variable in the return function, but I'm getting undefined. I understand that this is because JavaScript has asynchronous behavior.

I tried to make the blogs export function async and used await, but it gave an error: "Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead."

Even I tried some other options, such as putting the return function inside an IIFE, but this didn't display the "Welcome to my blogs" line.

Hoping for a solution.

英文:

I'm using Next.js, where im new to Next.js; I have some knowledge in javaScript
I have written some code to get the API of my JSON_file(which is my data that needs to be displayed in /blogs webpage);

import React from &#39;react&#39;

const blogs = () =&gt; {
 var element
 (async()=&gt;{

  var data=await fetch(&quot;http://localhost:3000/api&quot;)
  data=await data.json();
  console.log(data);
  console.log(data.length)
  for (let index = 0; index &lt; data.length; index++) {
     element = data[index];
    // document.getElementById(tilte).innerHTML+=element[&quot;title&quot;]
    console.log(element[&quot;title&quot;])
  }
})()

in this above code, I have written some code to fetch data from API, but the above-commented code( document.getElementById(tilte).innerHTML+=element["title"] ) is not working and getting error as( Cannot read properties of null (reading 'innerHTML') ) but I wanted to print this in my web page so I tried to print in return function which also does not worked

  return (
    &lt;&gt;
    &lt;div&gt;&lt;h1&gt;
      Welcome to my  blogs
    &lt;/h1&gt;
    &lt;/div&gt;
  
    &lt;div id=&quot;tilte&quot;&gt;
          {console.log(element[&quot;title&quot;])}
    &lt;/div&gt;
    &lt;/&gt;
  )
  
}


export default blogs

in this, I tried to console.log my element variable in the return function but I'm getting undefined, I understood that this is because JavaScript has Asynchronous behavior

I tried to make blogs export function async and aw

  const blogs = async () =&gt; {
  var element
  await (async () =&gt; {

but given as an error( Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead )

even I tried some other options of putting return function inside iife but this will not even display welcome to my blogs line

hoping for solution,,

答案1

得分: 1

尝试使用useEffect()useState()来在获取数据后更新博客的状态,就像这样:

import React, { useEffect, useState } from 'react';

const Blogs = () => {
  const [content, setContent] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      let data = await fetch('http://localhost:3000/api');
      data = await data.json();
      console.log(data);
      console.log(data.length);
      for (let index = 0; index < data.length; index++) {
        setContent((prevState) => prevState + data[index]);
      }
    }
    fetchData();
  }, []);

  return (
    <>
      <div><h1>
        欢迎来到我的博客
      </h1></div>

      <div id="tilte">
        {content}
      </div>
    </>
  )
}
英文:

Try using useEffect() with useState() to update the state of the blog once you fetch the data, like this:

import React, {useEffect, useState} from &#39;react&#39;

const Blogs = () =&gt; {
  const [content, setContent] = useState(&quot;&quot;);

  useEffect(() =&gt; {
    const func = async () =&gt;{
      let data = await fetch(&quot;http://localhost:3000/api&quot;);
      data = await data.json();
      console.log(data);
      console.log(data.length);
      for (let index = 0; index &lt; data.length; index++) {
        setContent ((prevState) =&gt; prevState + data[index]);
      }
    }
    func();
  }, []);

  return (
    &lt;&gt;
      &lt;div&gt;&lt;h1&gt;
        Welcome to my  blogs
      &lt;/h1&gt;
      &lt;/div&gt;

      &lt;div id=&quot;tilte&quot;&gt;
        {content}
      &lt;/div&gt;
    &lt;/&gt;
  )
}

huangapple
  • 本文由 发表于 2023年1月7日 10:58:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75037819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定