首页 > 解决方案 > 将状态从一个组件传递到另一个组件

问题描述

所以我尝试在反应 laravel mix 和上帝中制作一个登录系统......这太难了。现在我有了一个想法来制定正确的逻辑,这需要我将状态从一个组件传递到另一个组件。在这种情况下,我尝试将状态从 login.js 传递给 master.js 组件。

我试图通过的状态是isLogged

Login.js 代码

  constructor(props){
    super(props);
    this.state = {userEmail: '', userPassword:'', isLogged: false, isLoggedfail: false, dataUser:{}};

    this.handleChange1 = this.handleChange1.bind(this);
    this.handleChange2 = this.handleChange2.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange1(e){
    this.setState({
      userEmail: e.target.value
    })
  }
  handleChange2(e){
    this.setState({
      userPassword: e.target.value
    })
  }
  handleSubmit(e){
    e.preventDefault();
    const usern = {

      email: this.state.userEmail,
      password: this.state.userPassword

    }
    let uri = 'http://localhost:8000/api/auth/login';
    axios.post(uri, usern).then(response => {
          this.setState({ isLogged: true });
          this.setState({dataUser: response.data.data}) 
          sessionStorage.setItem("key", this.state.dataUser.id_user)
          console.log(this.state.dataUser.id_user)
          this.props.history.push('/');
        }
    ).catch(error => {
  console.log("Error:" + error.message)
  this.setState({isLoggedfail: true})
})
  }

和master.js

constructor(props){
    super(props);
    this.state = {cari: '', diCari:false, isLoggedIn:false};

    this.handleChange1 = this.handleChange1.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange1(e){
    this.setState({
      cari: e.target.value
    })
  }

  handleSubmit(e){
          this.setState({ diCari: false });
  console.log("makan")
  const cari = {
    cari: this.state.cari
    }

      this.setState({ diCari: true });
      this.props.history.push("/search/"+this.state.cari) 
    }
  componentDidMount(){
  if(sessionStorage.getItem("key") !== null)  {
    this.setState({Logged:true})
    }
    else{
      this.setState({Logged:false})
    }
  }

    componentDidUpdate(props){
      if(this.state.logout){
        this.setState({logout:false})
        this.props.history.push('/')
      }
      else if(this.state.Logged){
    if(sessionStorage.getItem("key") !== null)  {
       this.setState({Logged:false})
      }
    }
}

路线:

render(){
    return(
      <HashRouter>

  <div className="wrap">
  <Master/>
  <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/home" component={Home} />
    <Route path="/login" component={Login} />
    <Route path="/register" component={Register} />
    <Route exact path="/search/:userId" component={Search} />
    <Route exact path="/carts/:userId" component={Keranjang} />
    <Route exact path="/produk/:userId" component={Product} />
    </Switch>
    </div>
      <Footer/>
    </HashRouter>
  );
}
}
if (document.getElementById('app')) {
        ReactDOM.render(<Index />, document.getElementById('app'));
      }

请注意,我尝试使用isLogged状态,componentDidupdate但现在我正在使用导致无限循环的会话检查。

非常感谢你的帮助!我已经被困了 3 天,使身份验证做出反应。

标签: javascriptreactjslaravel

解决方案


我想看看你的渲染功能有什么?要共享状态,最好使用回调函数并将数据发送回层次结构。

同样在您的promise.then中,您正在设置状态,然后执行没有意义的history.push:-因为如果您被引导离开页面(卸载),您将失去本地状态

此外,最好将您的函数命名为比 handleChange1 handleChange2 更好的名称


推荐阅读