首页 > 解决方案 > hide and show external components in react

问题描述

I am newbie in react and I have some trouble that I'd like to solve. I would like to know how can I show and hide react components before and after to do a rest call. I have the follow component:

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;

And I would like to show this component in other module before to call a rest api and hide this component after the data come. The ideia is some like this:

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>

How can I do it?

标签: reactjs

解决方案


You can create state that dictates whether the loading spinner is visible or not. And append one last .then in the promise chain to modify it.

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>

Then utilize ternary syntax on the spinner to determine visibility.


推荐阅读