[英]state of list is not getting update
我无法弄清楚为什么列表状态没有得到更新。 response.data 正在控制台中打印。
function Products(){
const [List ,setList] = useState([])
useEffect(() => {
axios.get("http://localhost:8900/courses").then((response)=> {
setList((prevList) => [...prevList, response.data]};
console.log( response.data)
console.log( "list",List)
});
}, []);
我期待列表的状态用数据更新
我试过这个演示,它运行良好。 您需要注意 setList 根据此答案是异步的。
function apiCall() {
return new Promise((resolve) => setTimeout(() => resolve(3), 5000));
}
export default function App() {
const [List, setList] = React.useState([1, 2]);
React.useEffect(() => {
apiCall().then((response) => {
setList((prevList) => [...prevList, response]);
});
}, []);
return <div>{List.join(' ')}</div>;
}
您在 Axios 内部的 setList 上有错字,您忘记关闭括号并使用大括号代替。
setList((prevList) => [...prevList, response.data]}; // it should be ])
function Products() { const [List, setList] = React.useState([]) React.useEffect(() => { axios.get("https://jsonplaceholder.typicode.com/users").then((response)=> { setList((prevList) => [...prevList, response.data]); // Error was here console.log(response.data) console.log( "list",List) }); }, []); return ( <div>List: {JSON.stringify(List)}</div> ) } const rootElement = document.getElementById("root"); ReactDOM.render(<Products />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <div id="root"></div>
你可以刷新页面。 我希望它有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.