score:0

Accepted answer

in tools.js

let loadingstatesetter = null

export function setloadingstatesetter(setter) {
    loadingstatesetter = setter
    return () => loadingstatesetter = null
}

export function setloadingstate(value) {
    if (loadingstatesetter !== null) loadingstatesetter(value)
}

in loading.js:

import { setloadingstatesetter } from './tools.js'

export default class loading extends react.component {
    constructor(props) {
        super(props)
        this.state = {
            display: 'none'
        }
    }

    render() {
        return (
            <div classname="loading" style={{display: this.state.display}}>
                <span></span>
            </div>
        )
    }

    componentdidmount() {
        this.removestatesetter = setloadstatesetter((value) => {
            this.setstate((state) => ({
                ...state,
                display: value,
            })
        })
    }

    componentwillunmount() {
        this.removestatesetter()
    }
}

usage:

import { setloadingstate } from './tools.js'

function xxx(){
    setloadingstate('some value')
}

score:0

while you can easily expose a setstate function externally, it acts just like any other function, its not usually a good idea. you should instead consider rewriting your loading component to use the property object to tell it if its loading and track the loading state higher up the component tree where it is accessible by things that would want to change its status.

score:0

i think you can using redux as store manager global state https://redux.js.org/ another way pass it through props and handle it at parent component


Related Query

More Query from same tag