简体   繁体   中英

Set state from another component React js

I have the following structure in index.js :

<MyAppBar // + properties/>
 <Route path={path} component={Login}/>

MyAppBar.js

 class MyAppBar extends React.Component {

state = {
  auth: false,
  anchorElement: null
};

handleLogin(){
  this.setState({auth:true});
}

//another code
//end component

export default withStyles(styles)(MyAppBar)

I want to update MyAppBar state auth flag to be true from within the Login component action handler (ie handleLogin ), but I do not know how.

I've tried with importing MyAppBar (all component) on the Login page, but it says that

MyAppBar.handleLogin(); 

is not a function... Thank you!

Thank you!

I don't think for this simple paradigm you'll need to go through all the hassle of setting redux up(I love Redux, but sometimes we don't have to use it)

Here's how you could implement it with the new context .

编辑React挂钩

It's farily simple and nice to use. Check it here Let me know if that isn't clear.

Login should be a children component of MyAppBar. Then you could pass function handleLogin as a props to Login.

You should use REDUX.

Mostly because it lets you have a state that any component can read or can be synced with.

I rarely use react's state/setState.

In most cases redux state is good to change/watch.

its better to use redux in such scenarios, as that makes communication between components very easy. Else if you want to go the hard way, then create a parent component, that will wrap both login and MyAppBar.

  class ParentComp extends Component{
      constructor(props){ 
         super(props);
         this.state={
             isLoggedIn:false
         };
        this.setLoginState=this.setLoginState.bind(this);
      }
      setLoginState(value){
          this.setState({isLoggedIn:value});
      }

       render(){
         return(<div>
                   <MyAppBar isLoggedIn={this.state.isLoggedIn} />
               <Route path={path} render={props=><Login {..props} setLoginState={this.setLoginState}/>}/>
                </div>);
       }
  }

in your LoginComponent call the setLoginState method

   this.props.setLoginState(true);

and in your myappbar component use the isLoggedIn prop to render conditionally

   renderLogin(){
     if(this.props.isLoggedIn){ 
          // return loggedin jsx
     }else{
         return the alternative
     }
   }

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