我有一个简单的模态,我在其中写一些数据并提交到数据库。我正在尝试在按钮上实现简单的加载,因此用户会收到反馈。不幸的是,这不起作用。
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>
谢谢! :)
答案 0 :(得分:1)
在等待调用之前触发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)))
}
}
}
答案 1 :(得分:1)
您想要在获取数据之前将isLoading
设置为true
,然后在异步请求完成后将isLoading
设置为false
。
示例
function getList() {
return new Promise(function(resolve) {
setTimeout(() => resolve([1, 2, 3]), 1000);
});
}
class App extends React.Component {
state = {
isLoading: false,
show: false,
list: []
};
onSubmit = event => {
this.setState({ isLoading: true });
getList().then(list => {
this.setState({
isLoading: false,
list,
show: false
});
});
};
render() {
return (
<button
onClick={this.onSubmit}
disabled={this.state.isLoading}
>
{this.state.isLoading ? "Loading..." : "OK"}
</button>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>