gpt4 book ai didi

reactjs - 在 React 中隐藏和显示外部组件

转载 作者:行者123 更新时间:2023-12-02 02:58:52 24 4
gpt4 key购买 nike

我是 react 新手,我有一些问题想要解决。我想知道如何在进行休息调用之前和之后显示和隐藏 react 组件。我有以下组件:

class Loading {

render(){
return (
<div >
<Modal isOpen={true} centered >
<ModalHeader>Loading...</ModalHeader>
<ModalBody >
<div align='center' className="mt-2 mb-2">
<Spinner style={{ width: '4rem', height: '4rem' }} color="primary" />
</div>
</ModalBody>
</Modal>
</div>
)
}
}export default Loading;

我想在调用rest api之前在其他模块中显示这个组件,并在数据到来后隐藏这个组件。这个想法是这样的:

class List extends Component {
constructor(props) {
super(props)
this.state = {
show : false
}
}

// HERE I WOULD LIKE TO SHOW THE LOADING COMPONENT

callRestApi = () => {

axiosAuth.get(url, getConfig())
.then(response => {
console.log(response.data)
this.setState({
eventos: response.data
})
}).catch(error => {
console.log(error);
return null
});

// HERE I WOULD LIKE TO HIDE THE LOADING COMPONENT
}

render() {
return(
<div>
<Button className="mr-2" color="primary" size="sm" onClick={this.callRestApi}>List All</Button>
</div>

我该怎么做?

最佳答案

您可以创建指示加载微调器是否可见的状态。并在 Promise 链中追加最后一个 .then 来修改它。

class List extends Component {
constructor(props) {
super(props)
this.state = {
show : false,
loaderVisible: true
}
}

// HERE I WOULD LIKE TO SHOW THE LOADING COMPONENT

callRestApi = () => {

axiosAuth.get(url, getConfig())
.then(response => {
console.log(response.data)
this.setState({
eventos: response.data
})
}).catch(error => {
console.log(error);
return null
}).then(() => {
this.setState({loaderVisible: false });
});
}

render() {
return(
<div>
{
this.state.loaderVisible? <Loading /> : ''
}
<Button className="mr-2" color="primary" size="sm" onClick={this.callRestApi}>List All</Button>
</div>

然后在微调器上使用三元语法来确定可见性。

关于reactjs - 在 React 中隐藏和显示外部组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60435446/

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