在 React 中单击按钮获取数据
要在 React 中单击按钮获取数据:
- 在按钮元素上设置
onClick
属性。 - 每次单击该按钮时,都会发出一个 HTTP 请求。
- 更新状态变量并渲染数据。
如果我们使用 axios
,请向下滚动到下一个代码片段。
import {useState} from 'react';
const App = () => {
const [data, setData] = useState({data: []});
const [isLoading, setIsLoading] = useState(false);
const [err, setErr] = useState('');
const handleClick = async () => {
setIsLoading(true);
try {
const response = await fetch('https://reqres.in/api/users', {
method: 'GET',
headers: {
Accept: 'application/json',
},
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
console.log('result is: ', JSON.stringify(result, null, 4));
setData(result);
} catch (err) {
setErr(err.message);
} finally {
setIsLoading(false);
}
};
console.log(data);
return (
<div>
{err && <h2>{err}</h2>}
<button onClick={handleClick}>Fetch data</button>
{isLoading && <h2>Loading...</h2>}
{data.data.map(person => {
return (
<div key={person.id}>
<h2>{person.email}</h2>
<h2>{person.first_name}</h2>
<h2>{person.last_name}</h2>
<br />
</div>
);
})}
</div>
);
};
export default App;
我们在按钮元素上设置了 onClick
属性,因此每次单击按钮时,都会调用 handleClick
函数。
我们将 handleClick
函数标记为异步,因此我们可以使用 await
关键字来等待其中的 Promises。
在
handleClick
函数中,我们等待 http 请求完成并更新状态变量。
此示例使用本机 fetch API,但如果我们也使用 axios 包,该概念也适用。
这是使用 axios
包在单击按钮时获取数据的方法。
如果我们决定使用 axios
,请确保通过运行 npm install axios
安装了该软件包。
import {useState} from 'react';
import axios from 'axios';
const App = () => {
const [data, setData] = useState({data: []});
const [isLoading, setIsLoading] = useState(false);
const [err, setErr] = useState('');
const handleClick = async () => {
setIsLoading(true);
try {
const {data} = await axios.get('https://reqres.in/api/users', {
headers: {
Accept: 'application/json',
},
});
console.log('data is: ', JSON.stringify(data, null, 4));
setData(data);
} catch (err) {
setErr(err.message);
} finally {
setIsLoading(false);
}
};
console.log(data);
return (
<div>
{err && <h2>{err}</h2>}
<button onClick={handleClick}>Fetch data</button>
{isLoading && <h2>Loading...</h2>}
{data.data.map(person => {
return (
<div key={person.id}>
<h2>{person.email}</h2>
<h2>{person.first_name}</h2>
<h2>{person.last_name}</h2>
<br />
</div>
);
})}
</div>
);
};
export default App;
如果我们使用 axios
,请确保通过在项目的根目录中运行 npm install axios
来安装包。
使用 axios
包时的语法更简洁一些,我们需要处理的实现细节更少,但概念是一样的。
我们必须在按钮元素上设置 onClick
属性,并在每次单击按钮时发出 http 请求。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。