简体   繁体   English

在按钮单击时反应获取数据

[英]react fetch data on button click

I'm trying to fetch data in react.我试图在反应中获取数据。 The problem is i have to click on button twice to get that data.问题是我必须单击按钮两次才能获取该数据。 Although i don't get data on first click it somehow renders if I add JSON.stringify to it.虽然我没有在第一次点击时获得数据,但如果我将 JSON.stringify 添加到它,它会以某种方式呈现。 If I don't add JSON.stringify it returns undefined.如果我不添加 JSON.stringify 它返回未定义。 If anyone know what this is please help me如果有人知道这是什么请帮助我

without clicking无需点击
on first click第一次点击
on second click第二次点击

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'));
 }

The problem was that setStudents is an asynchronous function, so I just made student object and added to it loading property问题是 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 hooks are async so when you are running console.log(students) right after running setStudents(data) it is still not populated, however the 2nd time you click the button it is already populated from the first time you clicked it. React 钩子是异步的,因此当您在运行setStudents(data)setStudents(data)运行console.log(students)它仍然没有填充,但是第二次单击按钮时,它已经从第一次单击开始填充了。

If you want to console the result right after the state setter runs you can see this answer on another question.如果您想在状态设置器运行后立即控制台结果,您可以在另一个问题上看到这个答案

setStudent is an asynchronous function. setStudent是一个异步函数。 This means the value of students won't change immediately after you call setStudents .这意味着价值students ,你不打电话后立即更改setStudents

Try shifting the console.log outside the handleClick function.尝试将 console.log handleClick函数之外。 Like this -像这样 -

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'));
 }

Initially, the value will be an empty string, then it will change to the value from api/foo最初,该值将是一个空字符串,然后它将更改为来自api/foo的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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