gpt4 book ai didi

javascript - 在提交时 react js显示加载按钮

转载 作者:行者123 更新时间:2023-11-29 18:44:40 26 4
gpt4 key购买 nike

我有一个简单的模式,我在其中写入一些数据并提交到数据库。我正在尝试在按钮上实现一个简单的加载,以便用户收到反馈。不幸的是,这不起作用。

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>

谢谢! :)

最佳答案

您想在获取数据之前将 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>

关于javascript - 在提交时 react js显示加载按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54722761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com