useEffect(async () =>
{
const fetchData = async () =>
{
const result = await axios("")
setposts(result.data)
}
fetchData();
}, [])
渲染:
posts.map(post => <li>{post.name}</li>)
Json 文件:
[
{
"id": 1,
"vendor": "Gap",
"name": "Men's Pullover Sweatshirt",
"image_src": ["https://cdn.shopify.com/s/files/1/0455/2176/4502/files/Sweater_0.jpg?v=1603266982"],
"price": "74",
"tag": "T-shirt",
"compare_at_price": "200",
"options": [
{
"id": "1010",
"name": "Size",
"value": "US 8"
}, {
"id": "1011",
"name": "Size",
"value": "US 9"
}, {
"id": "1012",
"name": "Size",
"value": "US 10"
}, {
"id": "1013",
"name": "Size",
"value": "US 11"
}, {
"id": "1014",
"name": "Size",
"value": "US 13"
}
]
},
我面临从 json 文件中检索数据的问题,就像我无法渲染数据一样,请帮忙解决这个问题
映射数据时出错
我面临从 json 文件中检索数据的问题,就像我无法渲染数据一样,请帮忙解决这个问题
答案 0 :(得分:0)
useEffect(() =>
{
const fetchData = async () =>
{
const result = await axios.get("https://cdn.shopify.com/s/files/1/0455/2176/4502/files/products.json")
setposts(result.data)
}
fetchData();
}, [])
posts?.map(post => <li>{post.name}</li>)
答案 1 :(得分:0)
问题在于这个文件:https://cdn.shopify.com/s/files/1/0455/2176/4502/files/products.json
它返回一个无效的 JSON 字符串。因此,当您的 axios 获取其内容时,会将您的 posts
变量设置为一个简单的字符串,该字符串显然无法映射。因此出现错误。
axios 没有将其转换为 JS 数组的原因是该文件不包含要解析的有效 JSON。
答案 2 :(得分:0)
这对您不起作用的原因是,result.data
是一个字符串,而不是一个数组。
您必须使用 JSON.parse
将 result.data 转换为数组
此外,您使用的 json 有一个训练逗号,必须对其进行处理,JSON.parse
才能工作
以下代码对我有用:
export default function App() {
const [posts, setposts] = useState([]);
useEffect(async () => {
const fetchData = async () => {
const result = await axios.get(
"https://cdn.shopify.com/s/files/1/0455/2176/4502/files/products.json"
);
let regex = /\,(?!\s*?[\{\[\"\'\w])/g;
let correct = result.data.replace(regex, "");
setposts(JSON.parse(correct));
};
fetchData();
}, []);
return (
<div className="App">
{posts.map((post) => (
<li>{post.name}</li>
))}
</div>
);
}