我正在呼叫一個API並正確地獲取到回應,但是在回應函數外部,同樣的回應值顯示為空。我需要在頁面加載時從外部獲取它。以下是程式碼:
import React, { useState, useEffect,useRef, useMemo } from 'react'; import axios from 'axios'; function Test() { const [state, setState] = useState([]); useEffect(() => { axios.get(`https://jsonplaceholder.typicode.com/todos/1`) .then(res => { setState(res.data); }) console.log(state) }, []); } export default Test;
P粉8525780752023-09-18 00:30:51
我認為你只需要在useEffect之外的地方安慰這個值,像這樣:
import React, { useState, useEffect,useRef, useMemo } from 'react'; import axios from 'axios'; function App() { const [state, setState] = useState({}); useEffect(() => { axios.get(`https://jsonplaceholder.typicode.com/todos/1`) .then(res => { // console.log(res.data) setState(res.data); }) },[]); console.log(state) } export default App;