【发布时间】:2018-12-26 14:27:15
【问题描述】:
我向 api 发送请求,只有当我从 api 接收到数据时,我才使用该数据设置状态,否则我将状态设置为未定义。 但有时这些数据返回为空(那些数据就是这样),所以在这种情况下,我将 setState 设置为未定义。工作正常,除非我没有输入并尝试发送请求,然后我得到“未处理的拒绝(SyntaxError):JSON 输入的意外结束” 由于我每次都将状态设置为未定义,除非我从 api 获取数据,为什么会发生这种情况?
尝试用 try/catch 包装它以查看错误,但它甚至没有启动。然后我检查了拼写错误等。还尝试将整个 if 语句包装到另一个,它只会在从 api 接收到的数据为真时运行,但它没有做任何事情。
getPictureFunc = async event => {
event.preventDefault();
//here i grab values from user input in Form.js
const year = event.target.elements.year.value;
const month = event.target.elements.month.value;
const day = event.target.elements.day.value;
//here i make request call to NASA's API:
const api_call = await fetch(
`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?
earth_date=${year}-
${month}-${day}&api_key=${API_KEY}`
);
//here i save received data to JSON:
const receivedDataFromApi = await api_call.json();
if (year && month && day) {
console.log(receivedDataFromApi);
this.setState({
sol: receivedDataFromApi.photos[0].sol,
earth_date: receivedDataFromApi.photos[0].earth_date,
img: receivedDataFromApi.photos[0].img_src,
error: ""
});
} else {
this.setState({
sol: undefined,
earth_date: undefined,
img: undefined,
error: "no pics for this day, try another one"
});
}
};
【问题讨论】:
标签: reactjs