繁体   English   中英

如何使用 fetch function 将来自 Api 的响应分配给数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM