javascript 如何控制Reactjs中useEffect内部的axios结果

yyyllmsg  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(144)

我正在使用Reactjs和nextjs。现在我正在使用Axios通过API获取数据,但无法在页面上显示。为此,我尝试在useEffect中使用console.log,但没有显示任何内容。我如何使用console.log并在页面中显示数据?以下是我当前的代码

import dynamic from 'next/dynamic';
import React, { FormEventHandler, useRef } from 'react';
import { Editor } from '@tinymce/tinymce-react';
import { useEffect, useState } from "react";
import axios from 'axios';
import $ from 'jquery';

const Test=()=>{
const[post,setPosts]=useState([]);

useEffect(() => {
    const getPosts = async () => {
      const { data: res } = await axios.get(
        "https://diggdevelopment.com/blackstallion_new/api/get_demodata/"
      )
      console.log('here is data'+ res);
     setPosts(res);
     };
    getPosts();
  }, []);

return(
    <>
      <table className="table">
        <thead>
            <tr>
              <th>Id</th>
              <th>Title</th>
              <th>Delete</th>
            </tr>
          </thead>
          <tbody>
          {post.length > 0 ? (
                              post.map((post: any, index: number) => (
                             <tr key={post.id}>
                                     <td>{post.id}</td>
                                     <td>{post.title}</td>
                                </tr>
                              ))
                            ) : (
                              <></>
                            )}
            </tbody>
    </table>
 </>
);

  }

  export default Test;
sgtfey8w

sgtfey8w1#

应使用try-catch块
您可以尝试下面的代码:

const getPosts = async () => {
    try {
      const res = await axios.get(
        "https://diggdevelopment.com/blackstallion_new/api/get_demodata/"
      );
      console.log("here is data", res);
      setPosts(res.data.blogs);
    } catch (err) {
      console.log(`ERROR: ${err}`);
    }
  };

  useEffect(() => {
    getPosts();
  }, []);

现场演示点击此处:https://codesandbox.io/s/intelligent-rgb-m0zglq?file=/src/App.js:304-594

相关问题