简体   繁体   English

从 React 中的另一个组件更新组件的 state

[英]Updating state of a component from another component in React

In a React project I had a components named Auth.jsx that manage authentication and routing.React项目中,我有一个名为Auth.jsx的组件,用于管理身份验证和路由。 Like this:像这样:

let ComponentToShow;
let path="/";
let isSMSSent = false;

function Auth(){

       if(isSMSSent){
          let args = {
             onBackClick:handleBackClick,
           }
           path = "/receive";
           ComponentToShow = <CheckSMSCode args={args} />;
       else{
            let args = {
                onClick:handleSendSMSClick,
            }

            path = "/send";
            ComponentToShow = <SMSAuth args={args} />;

       }

       return(
        <Router>
        <Redirect to={path} />
          <Switch>

            <Route path="/send">
                {ComponentToShow}
            </Route>

            <Route path="/receive">
                {ComponentToShow}
            </Route>

          </Switch>
      </Router>
    );
}

Now, What I want to do is that, if there is an error in the Auth.jsx component, Show an error message in the SMSAuth.jsx component.现在,我想要做的是,如果SMSAuth.jsx组件中有错误,则在Auth.jsx组件中显示错误消息。 Because the brain of the app is Auth.jsx , I handle errors here, but I want to show errors inside each component that Im showing.因为应用程序的大脑是Auth.jsx ,我在这里处理错误,但我想在我显示的每个组件中显示错误。 In fact i want to update state in the another component and the UI updates.事实上,我想在另一个组件和 UI 更新中更新 state。

I googled this and some people says Redux can help this.我用谷歌搜索了这个,有人说 Redux 可以帮助解决这个问题。 but i don't want to use Redux and stick to pure React.但我不想使用Redux并坚持使用纯 React。 What I have to do to solve my problem?我需要做什么来解决我的问题? using Redux is mandatory and Im thinking wrong about that?使用 Redux 是强制性的,我想错了吗?

What Im thinking about that is connecting two component via props and creating a reference to the main component to use resources, but I don't know how to do that.我在想的是通过道具连接两个组件并创建对主要组件的引用以使用资源,但我不知道该怎么做。 I know using React.context can have shared values between components but changing in the shared value doesn't change the UI because state not updated.我知道使用React.context可以在组件之间共享值,但更改共享值不会更改 UI,因为 state 未更新。

You can use context, here is an example using counter您可以使用上下文,这里是一个使用计数器的例子

 const CounterContext = React.createContext(); const CounterProvider = ({ children }) => { const [count, setCount] = React.useState(0); const up = React.useCallback( () => setCount((count) => count + 1), [] ); const down = React.useCallback( () => setCount((count) => count - 1), [] ); return ( <CounterContext.Provider value={{ count, up, down, }} > {children} </CounterContext.Provider> ); }; const Counter = React.memo(function Counter() { const { up, down, count } = React.useContext( CounterContext ); return ( <div> <div> <button onClick={up}>+</button> </div> <div>{count}</div> <div> <button onClick={down}>-</button> </div> </div> ); }); const App = function () { return ( <CounterProvider> <Counter /> </CounterProvider> ); }; ReactDOM.render(<App />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

Your component probably doesn't re render because you are mutating some value that is not managed in any React or Redux state. The counter works because count comes from React state and is not mutated when changed.您的组件可能不会重新呈现,因为您正在改变一些未在任何 React 或 Redux state 中管理的值。计数器工作是因为计数来自 React state 并且在更改时不会发生变化。

Maybe use callback function like this;也许像这样使用回调 function;

const [isSMSSent, setisSMSSent] = useState(false);

setSmsSent = (value) => {setisSMSSent(value)}

<CheckSMSCode args={args} setSmsSent={setSmsSent} />

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

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