我正在使用 ReactJS 構建一個網站,該網站使用我計算機上本地存在的 JSON 來獲取要填寫的資訊。這是 index.js 檔案:-
import React from 'react';
import data from 'notes.json';
class BlogList extends React.Component {
constructor(props){
super(props);
this.state={
items:[],
loaded: false
};
}
/* useEffect()=>{
return function(){
}
},[deep])
*/ //Similar to ComponentDidUnMount();
componentDidMount(){
fetch(data)
.then(response => response.json())
.then(json => {
this.setState({
items: json,
loaded: true,
})
})
}
render() {
const {items, loaded} = this.state;
if(!loaded){
return <h3>Loading........</h3>
}
return (
<div className="content-container" >
{
items.map((item)=>(
<div key={item.id}>
<p>
{item.postId}
</p>
<p>
{item.id}
</p>
<p>
{item.name}
</p>
<p>
{item.email}
</p>
<p>
{item.body}
</p>
<hr/>
</div>
))
}
</div>
);
}
}
export default BlogList;
JSON檔案在這里: -
[
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "[email protected]",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
},
{
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "[email protected]",
"body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
},
{
"postId": 1,
"id": 3,
"name": "odio adipisci rerum aut animi",
"email": "[email protected]",
"body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
},
{
"postId": 1,
"id": 4,
"name": "alias odio sit",
"email": "[email protected]",
"body": "non et atque\noccaecati deserunt quas accusantium unde odit nobis qui voluptatem\nquia voluptas consequuntur itaque dolor\net qui rerum deleniti ut occaecati"
}
]
它在控制臺中不斷給我這個錯誤: - 未處理的承諾拒絕:SyntaxError:字串與預期的模式不匹配。
uj5u.com熱心網友回復:
如果服務器的回應是文本,但您嘗試使用 res.json() 將其決議為 JSON,您可能會收到此錯誤。
fetch(serverUrl, {method: 'GET'})
.then((res) => res.json())
res.text()
如果服務器回傳文本是合適的。
在這種情況下,Safari 曾經給我 OP 的錯誤,但 Chrome 更具體:“位置 0 處的 json 中的意外令牌 W”—— res.json() 期望字串的第一個字符是 { 或 [ 因為這就是JSON 開始。
或者,正如 Safari 所說,“字串與預期的模式不匹配”??。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/434108.html
標籤:javascript 反应 网络
