Javascript 创建一个按钮加载状态
我有一个执行API调用的按钮。我想在加载数据时显示加载状态 这是他们在react文档中处理网络请求的方式Javascript 创建一个按钮加载状态,javascript,reactjs,Javascript,Reactjs,我有一个执行API调用的按钮。我想在加载数据时显示加载状态 这是他们在react文档中处理网络请求的方式 function simulateNetworkRequest() { return new Promise(resolve => setTimeout(resolve, 2000)); } 这就是我需要的 function simulateNetworkRequest () { return new Promise(axios.post('http://localh
function simulateNetworkRequest() {
return new Promise(resolve => setTimeout(resolve, 2000));
}
这就是我需要的
function simulateNetworkRequest () {
return new Promise(axios.post('http://localhost:5000/'))
}
但它抛出了一个错误:
类型错误:axios\uuu网页包\u导入的\u模块\uu 1\uuuuuu默认值。a.post(…)不是函数 在功能组件中创建加载状态:
...
const [loading, setLoading] = React.useState(false)
const [data, setData] = React.useState([])
async function simulateNetworkRequest() {
setLoading(true)
const dataFetched = await axios.post('http://localhost:5000')
setData(dataFetched)
setLoading(false) //When it's finished
}
if (loading) return <p>Loading ...</p>
return (
<div>
{data.map(item => <p>item</p>)}
</div>
)
。。。
常量[loading,setLoading]=React.useState(false)
const[data,setData]=React.useState([])
异步函数simulateNetworkRequest(){
设置加载(真)
const dataFetched=等待axios.post('http://localhost:5000')
setData(数据获取)
setLoading(false)//当它完成时
}
如果(加载)返回加载
返回(
{data.map(item=>item)}
)
如果你想要一个按钮来改变他的状态,你可以这样使用
import * as React from "react";
import axios from "axios";
export default function App() {
const [isLoading, setIsLoading] = React.useState(false);
const handleClick = () => {
setIsLoading(true);
axios
.post("http://localhost:5000/")
.then(response => {
setIsLoading(false);
//set some data from response
})
.catch(error => {
setIsLoading(false);
//handle error
});
};
return (
<div className="App">
<button type="button" onClick={() => handleClick()}>
{isLoading ? `Loading` : `get data`}
</button>
</div>
);
}
import*as React from“React”;
从“axios”导入axios;
导出默认函数App(){
const[isLoading,setIsLoading]=React.useState(false);
常量handleClick=()=>{
设置加载(真);
axios
.post(“http://localhost:5000/")
。然后(响应=>{
设置加载(假);
//从响应中设置一些数据
})
.catch(错误=>{
设置加载(假);
//处理错误
});
};
返回(
handleClick()}>
{isLoading?`Loading`:`get data`}
);
}
从“axios”导入axios”
您这样做了吗?也许我错了,但axios是否已经返回了承诺?您的标题似乎有点误导,您正在尝试修复请求中的错误,问题中似乎没有提到加载状态。您发送post请求时没有正文吗?您只需返回axios.post('http://localhost:5000/)
因为它已经返回了一个承诺。