Javascript 提交时在按钮上显示加载
我有一个简单的模式,我写一些数据并提交到数据库。我试图在按钮上实现一个简单的加载,以便用户收到反馈。不幸的是,这不起作用Javascript 提交时在按钮上显示加载,javascript,reactjs,Javascript,Reactjs,我有一个简单的模式,我写一些数据并提交到数据库。我试图在按钮上实现一个简单的加载,以便用户收到反馈。不幸的是,这不起作用 constructor(props) { super(props); this.state = { isLoading: false, show: false, list: [] } } onSubmit = async event => { ref.onSnapshot(async doc => { if (d
constructor(props) {
super(props);
this.state = {
isLoading: false,
show: false,
list: []
}
}
onSubmit = async event => {
ref.onSnapshot(async doc => {
if (doc.data().status === 'accepted') {
const list = await this.get(name, age, id);
this.setState(prevState => ({
isLoading: !prevState.isLoading, // this doesn't work
list: list,
show: false // state for a modal
}, () => console.log('loading on submit', this.state.isLoading)))
}
}
}
<button
onClick={this.onSubmit}
disabled={this.state.isLoading ? true : false}>
{this.state.isLoading ? 'Loading...' : 'OK'}
</button>
构造函数(道具){
超级(道具);
此.state={
孤岛加载:false,
秀:假,,
名单:[]
}
}
onSubmit=异步事件=>{
参考onSnapshot(异步文档=>{
如果(doc.data().status==‘已接受’){
const list=wait this.get(姓名、年龄、id);
this.setState(prevState=>({
isLoading:!prevState.isLoading,//这不起作用
列表:列表,
show:false//模态的状态
},()=>console.log('提交时加载',this.state.isLoading)))
}
}
}
{this.state.isLoading?'Loading…':'OK'}
谢谢!:)在等待调用之前触发加载true,如下代码所示。
onSubmit = async event => {
ref.onSnapshot(async doc => {
if (doc.data().status === 'accepted') {
this.setState({
isLoading : true
})
const list = await this.get(name, age, id);
this.setState(prevState => ({
isLoading: false,
list: list,
show: false // state for a modal
}, () => console.log('loading on submit', this.state.isLoading)))
}
}
}
您希望在获取数据之前将
isLoading
设置为true
,然后在异步请求完成时将isLoading
设置为false
示例
函数getList(){
返回新承诺(函数(解析){
setTimeout(()=>resolve([1,2,3]),1000;
});
}
类应用程序扩展了React.Component{
状态={
孤岛加载:false,
秀:假,,
名单:[]
};
onSubmit=事件=>{
this.setState({isLoading:true});
getList()。然后(list=>{
这是我的国家({
孤岛加载:false,
列表
节目:假
});
});
};
render(){
返回(
{this.state.isLoading?“正在加载…”:“确定”}
);
}
}
render(,document.getElementById(“根”))代码>