简体   繁体   English

我如何将这个 function 从 app.js 中移出?

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

I intend to move out logic from my app.js.我打算从我的 app.js 中移出逻辑。 Right now, in app.js, I have a function that changes state of some variables in App.js.现在,在 app.js 中,我有一个 function 更改了 App.js 中一些变量的 state。 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.我想通过让 app.js 调用另一个组件中的 function(例如单击)来了解在 app.js 中更改 state 的正确方法是什么。

my app.js looks like the following:我的 app.js 如下所示:

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.我想将 stateChanger function 从 app.js 中移出,但仍保持相同的功能。 This in turn would allow me to call stateChanger from other classes easily.这反过来又使我可以轻松地从其他类调用 stateChanger。

The simplest solution (which is also the most difficult to scale) is to pass the function as a prop to its children.最简单的解决方案(也是最难扩展的)是将 function 作为 prop 传递给它的孩子。 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.但是通过在根级组件 App 上声明 state 并询问您通常如何从另一个组件修改它,我们可以解释这个问题本质上是关于如何处理全局 state。您可能需要考虑使用 Context API 或Redux,它们是专门为此目的创建的工具。

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.这里要记住的最重要的事情是,如果我们可以选择将 state 维护在合理接近它被使用和修改的地方,我们应该这样做而不是将其作为全局 state 的一部分处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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