簡體   English   中英

將 state 從一個組件傳遞到另一個組件

[英]passing state from one component to another

所以我嘗試在反應 laravel 混合和上帝中制作一個登錄系統......這太難了。 現在我有了一個想法來制定正確的邏輯,這需要我將 state 從一個組件傳遞到另一個組件。 在這種情況下,我嘗試將 state 從 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'));
      }

請注意,我嘗試在componentDidupdate中使用isLogged state 但現在我正在使用 session 檢查導致無限循環。

非常感謝你的幫助。 我已經被困了 3 天,使身份驗證做出反應。

我想看看你的渲染功能有什么? 要共享 state,最好使用回調函數並將數據發送回層次結構。

同樣在您的 promise.then 中,您正在設置 state,然后執行一個沒有意義的 history.push:-因為您將失去本地 state(如果您被引導離開頁面)

此外,最好將您的函數命名為比 handleChange1 handleChange2 更好的名稱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM