![](/img/trans.png)
[英]React/nextjs fetch data on a button click, but the button is in a different component
[英]react fetch data on button click
我試圖在反應中獲取數據。 問題是我必須單擊按鈕兩次才能獲取該數據。 雖然我沒有在第一次點擊時獲得數據,但如果我將 JSON.stringify 添加到它,它會以某種方式呈現。 如果我不添加 JSON.stringify 它返回未定義。 如果有人知道這是什么請幫助我
import React, {useState,useEffect} from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios'
function Example() {
const [students,setStudents] = useState('')
const [name,setName] = useState('')
const handleClick = async() => {
const data = await axios.get('api/foo')
setStudents(data)
console.log(students)
}
return (
<div className="container">
<h2>Example component</h2>
<button onClick = {handleClick}>Get students</button>
<div>
{JSON.stringify(students.data)}
</div>
</div>
);
}
export default Example;
if (document.getElementById('root')) {
ReactDOM.render(<Example />, document.getElementById('root'));
}
問題是 setStudents 是一個異步函數,所以我只是創建了 student 對象並將其添加到它的加載屬性中
const [students,setStudents] = useState({
data: '',
loading: true
})
const [name,setName] = useState('')
const handleClick = async() => {
const data = await axios.get('api/foo')
setStudents({
data: data,
loading: false
})
}
return (
<div className="container">
<h2>Example component</h2>
<button onClick = {handleClick}>Get students</button>
<div>
{students.loading?'':
students.data.data[0].name}
</div>
</div>
);
}
React 鈎子是異步的,因此當您在運行setStudents(data)
后setStudents(data)
運行console.log(students)
它仍然沒有填充,但是第二次單擊按鈕時,它已經從第一次單擊開始填充了。
如果您想在狀態設置器運行后立即控制台結果,您可以在另一個問題上看到這個答案。
setStudent
是一個異步函數。 這意味着價值students
,你不打電話后立即更改setStudents
。
嘗試將 console.log handleClick
函數之外。 像這樣 -
import React, {useState,useEffect} from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios'
function Example() {
const [students,setStudents] = useState('')
const [name,setName] = useState('')
const handleClick = async() => {
const data = await axios.get('api/foo')
setStudents(data)
}
console.log(students)
return (
<div className="container">
<h2>Example component</h2>
<button onClick = {handleClick}>Get students</button>
<div>
{JSON.stringify(students.data)}
</div>
</div>
);
}
export default Example;
if (document.getElementById('root')) {
ReactDOM.render(<Example />, document.getElementById('root'));
}
最初,該值將是一個空字符串,然后它將更改為來自api/foo
的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.