从另一个组件React js设置状态

时间:2018-10-17 11:07:30

标签: javascript reactjs react-router

我在 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)

我想从 Login 组件操作处理程序中将 MyAppBar 状态 auth 标志更新为 true (即 handleLogin ),但我不知道如何。

我已经尝试过在登录页面上导入 MyAppBar (所有组件),但是提示

MyAppBar.handleLogin(); 

不是功能...谢谢!

谢谢!

4 个答案:

答案 0 :(得分:1)

我认为对于这种简单的范例,您无需经历设置redux的所有麻烦(我喜欢Redux,但有时我们不必使用它)

在这里,您可以使用新的context来实现它。

Edit React Hooks

  

它非常简单易用。检查一下here   让我知道是否不清楚。

答案 1 :(得分:0)

登录应该是MyAppBar的子组件。然后,您可以将handleLogin函数作为登录的道具。

答案 2 :(得分:0)

您应该使用REDUX。

主要是因为它使您拥有任何组件都可以读取或可以与其同步的状态。

我很少使用react的state / setState。

在大多数情况下,可以更改/监视redux状态。

答案 3 :(得分:0)

在这种情况下使用redux更好,因为这使得组件之间的通信非常容易。否则,如果您想努力工作,则创建一个父组件,它将包装login和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>);
       }
  }

在LoginComponent中调用setLoginState方法

   this.props.setLoginState(true);

以及您的myappbar组件中  使用isLoggedIn属性进行条件渲染

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