簡體   English   中英

當道具改變時反應組件不重新渲染

[英]react component not rerendering when props change

我正在嘗試創建一個模式,詢問用戶是個人還是組織,然后顯示特定於該類型用戶的注冊模式。 這是我到目前為止:

家長:

this.state = {
   showInd: false,
   showOrg: false,  
};

changeInd = () => {
    this.setState({
       showInd: !this.state.showInd
     });
     this.props.onClose(); //this closes the initial modal
}
//exact same syntax for changeOrg

render(){

   return( 
     <div onClick={this.changeInd}>
          <FontAwesomeIcon icon={faUser} className="fa-7x icon"/> 
          <span>individual</span>
     </div>
     <div onClick={this.changeOrg}>
         <FontAwesomeIcon icon={faUsers} className="fa-7x icon"/>
         <span>organization</span>
    </div>
    <SignUpInd show={this.state.showInd} />
    <SignUpOrg show={this.state.showOrg} />
)}

和孩子:

render(){
   if (this.props.show){
   return( 
      <various sign up html>
   )}

}

當狀態改變時,父組件會重新渲染,但子組件不會,即使 props 發生變化。 我試過使用 componentDidUpdate,但是當道具在這里發生變化時也不會觸發。

我可能做錯了什么?

編輯:所以我意識到如果我用回調函數注釋掉關閉初始模態的行,signUpInd 模態將正確呈現。 為什么我不能兩者都做?

1.在父組件使用改變狀態的函數。

state = {
    showInd: false,
    showOrg: false,  
 };

 stateChange = () =>{
   this.setState({showInd:!this.state.showInd})
 }

2.在 div 上使用 onClick 函數,它將給出與現在相反的值,並將其作為道具傳遞給下一個組件

      <div onClick={this.stateChange}> //this onClick just flips showInd to the opposite of what it is currently - that's working properly
          
           <span>individual</span>
      </div>
     <SignUpInd show={this.state.showInd} stateChange= {this.stateChange} />

3.在另一端只需接收道具並控制台記錄它

        const {show,stateChange} = this.props
        console.log(show);

這有效:

import React from "react";
import SignUpInd from "./SignUpInd";
import SignUpOrg from "./SignUpOrg";
import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showInd: false,
      showOrg: false
    };
  }

  showInd = () => {
    this.setState((state) => ({ showInd: !state.showInd }));
  };

  showOrg = () => {
    this.setState((state) => ({ showOrg: !state.showOrg }));
  };

  render() {
    return (
      <React.Fragment>
        <div onClick={this.showInd}>
          <FontAwesomeIcon icon={faUser} className="fa-7x icon"/>
          <span>individual</span>
        </div>
        <div onClick={this.showOrg}>
          <FontAwesomeIcon icon={faUsers} className="fa-7x icon"/>
          <span>organization</span>
        </div>
        <SignUpInd show={this.state.showInd} />
        <SignUpOrg show={this.state.showOrg} />
      </React.Fragment>
    );
  }
}

暫無
暫無

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

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