我正在研究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;
你应该使用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