我正在调用一个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;