当我从一个叫做url的状态传递我的url获取api时,我从我的fetch api得到了这个错误。但是当我把url改成像'api/provinsi'这样的文本时我没有得到任何错误
读取数据出错:SyntaxError: Unexpected token<在JSON中位置0>在JSON中位置0>
useEffect(() => {
async function fetchMyAPI() {
await fetch(url, {
method: 'GET'
}).then(response => {
if(!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(response => {
if(response.Response === 'False') {
throw new Error(response.Error);
}
setData(response.data);
}).catch(error => {
console.log("Error fetching data: ", error);
});
}
fetchMyAPI();
}, []);
我是这样设置url状态的:
useEffect(() => {
if(idDaerah==1){
setColumn(['no', 'nama', 'aksi']);
setUrl('/api/provinsi');
} else if(idDaerah==2) {
setColumn(['no', 'nama', 'provinsi_id', 'aksi']);
setUrl('/api/kabupaten');
} else if(idDaerah==3) {
setColumn(['no', 'nama', 'kabupaten_id', 'aksi']);
setUrl('/api/kecamatan');
} else {
setColumn(['no', 'nama', 'kecamatan_id', 'aksi']);
setUrl('/api/desa');
}
}, []);
由于两个useEffect
同时运行,并且fetch函数第一次接收到url
作为empty string
,因此需要添加url
作为依赖项。
useEffect(() => {
async function fetchMyAPI() {
await fetch(url, {
method: 'GET'
}).then(response => {
if(!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(response => {
if(response.Response === 'False') {
throw new Error(response.Error);
}
setData(response.data);
}).catch(error => {
console.log("Error fetching data: ", error);
});
}
if(url !== ''){ //check if url is set i.e not an empty string
fetchMyAPI();
}
}, [url]); //add dependency, when url change then call api
或
您可以提供一个默认的url
,如:
const [url, setUrl] = useState('/api/provinsi');