我试图在我的react中使用api,但似乎无法在我的react前端加载响应。当我在浏览器上查看网络时,我可以看到响应,但它不会显示在网页上。
我的代码在下面,我似乎不知道出了什么问题。
import { useState, useEffect } from "react";
import axios from "axios";
import "./PrivateScreen.css";
const PrivateScreen = ({ history }) => {
const [error, setError] = useState("");
const [privateData, setPrivateData] = useState(null);
const url = "https://jsonplaceholder.typicode.com/users";
useEffect(() => {
if(!localStorage.getItem("authToken")) {
history.push("/login")
}
const fetchPrivateDate = async () => {
const config = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("authToken")}`,
},
};
try {
await axios.get(url, config)
.then(res => {
setPrivateData(res.data);
});
} catch (error) {
localStorage.removeItem("authToken");
setError("You are not authorized. Please login");
}
};
fetchPrivateDate();
}, [history]);
const logoutHandler = () => {
localStorage.removeItem("authToken");
history.push("/login");
};
return error ? (
<span className="error-message">{error}</span>
) : (
<>
<div style={{ background: "green", color: "white" }}>
{privateData.name}
</div>
<div><p>hello from this side</p></div>
<button onClick={logoutHandler}>Log Out</button>
</>
);
};
export default PrivateScreen;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
1条答案
按热度按时间ghhaqwfi1#
首先,你必须改变,而不是
const [privateData, setPrivateData] = useState(null);
const [privateData, setPrivateData] = useState([]);
调用数组数据时,我们希望初始化一个空数组然后,第二,当我们用希望像这样调用的帮助Map方法显示数组数据时,让我知道问题已经解决