简体   繁体   中英

How can i move this function out from app.js?

I intend to move out logic from my app.js. Right now, in app.js, I have a function that changes state of some variables in App.js. I want to learn what is the correct way to change the state inside app.js by letting app.js call a function (for example on click) that is in another component.

my app.js looks like the following:

const App = () => {
    const [opacity, opacitySet] = React.useState(1);
    const [showStep, setDisplayStep] = React.useState(true);
    const [isQrActive, setQrState] = React.useState(false);
    
/** code **/

  <ButtonContinue
    onClick={() => {
       stateChanger();
    }}
    style={{ backgroundColor: "black" }}
  >
    <p>cancel</p>
  </ButtonContinue>

/** lots of code **/

 function stateChanger() {  

   opacitySet(0);
     setTimeout(() => {

       opacitySet(1);
       setDisplayStep(!showStep);
       setQrState(!isQrActive);
     }, 400);

 }

/** and more code **/

}

I want to move the stateChanger function out from app.js, but still keep the same functionality. This in turn would allow me to call stateChanger from other classes easily.

The simplest solution (which is also the most difficult to scale) is to pass the function as a prop to its children. You could also create a custom hook. But by declaring the state on the root-level component App and asking about how you can generally modify it from another component, we can interpret that the question is essentially about how to handle global state. You may want to consider using the Context API or Redux, which are tools created specifically for that purpose.

The most important thing to remember here is that if we have the option of maintaining the state reasonably close to where it is being used and modified, we should do that instead of handling it as part of a global state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM