![](/img/trans.png)
[英]How to populate array with values from API using “fetch” in javascript function
[英]How to assign response from Api to an array using fetch function
我想在 Fruits 数组中分配响应我使用 fetch 从 Api 获取数据...但是当 console.log 时我得到空数组。这样: .then(data => Fruits);
let Fruits = []
useEffect(() => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
body: JSON.stringify({"dfdfdffd"})
};
fetch('https://d.com/audis/el/lt', requestOptions)
.then(response => response.json())
.then(data => Fruits);
}, []);
使用 state
const [fruits, setFruits] = useState([]);
useEffect(() => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
body: JSON.stringify({"firebase_id":"foCzPM8MgOtg1"})
};
fetch('https://d.com/audis/el/lt', requestOptions)
.then(response => response.json())
.then(data => setFruits(data);
}, []);
也许使用 state?
const [fruits, setFruits] = useState([])
useEffect(() => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
body: JSON.stringify({"firebase_id":"foCzPM8MgOtg1"})
};
fetch('https://d.com/audis/el/lt', requestOptions)
.then(response => response.json())
.then(data => setFruits(data));
}, []);
console.log(fruits);
您没有将data
分配给任何东西。 尝试:
fetch('https://d.com/audis/el/lt', requestOptions)
.then(response => response.json())
.then(data => Fruits = data);
此外,您应该使用 state 来存储信息。
const [fruits, setFruits] = useState();
fetch('https://d.com/audis/el/lt', requestOptions)
.then(response => response.json())
.then(data => setFruits(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.