我尝试获取获取请求的第一个元素的值。
在这里你可以看到我的代码 -> 获取请求的结果被分配给“data”变量。
const ListRezept = (props) => {
const url_id = props.params.id;
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
setTimeout(() => {
fetch('https://abc.4.azurestaticapps.net/data-api/rest/Rezept?$filter=RezeptId eq '+ url_id)
.then(res => {
if (!res.ok) { // error coming back from server
console.log("error");
throw Error('Could not fetch the data for that resource!');
}
return res.json();
})
.then(data => {
setIsPending(false);
setData(data.value);
setError(null);
})
.catch(err => {
if (err.name === 'AbortError') {
console.log('fetch aborted')
} else {
// auto catches network / connection error
setIsPending(false);
setError(err.message);
}
});
}, []);
// abort the fetch
return () => abortCont.abort();
}, [])
}
返回的data.value的结构(经过json()-解析后)你可以在这里看到
如何将返回的“json()”值的第一个元素分配给变量? 后来我想将这个“数据”变量传递到另一个页面并在 gatsby 中使用这些值。
伪代码:
// assign first element to a variable
const aenderungsdatum = data[0].aenderungsdatum
你的问题显然是这段代码:
.then(data => {
setIsPending(false);
setData(data.value);
setError(null);
})
第三行必须是
setData(data.data.value)
。如果您将 lambda 参数重命名为类似 json
: 的内容,它会变得更清晰
.then(json => {
setIsPending(false);
setData(json.data.value);
setError(null);
})