我正在使用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;
1条答案
按热度按时间sgtfey8w1#
应使用try-catch块
您可以尝试下面的代码:
现场演示点击此处:https://codesandbox.io/s/intelligent-rgb-m0zglq?file=/src/App.js:304-594