Skip to content

父组件在挂载过程中,子组件又更新父组件

司徒正美 edited this page Nov 7, 2017 · 1 revision
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script type='text/javascript' src="./dist/React.js"></script>
    <!-- <script src="./test/react.js"></script>
    <script src="./test/react-dom.js"></script> -->
    <script src="./lib/babel.js"></script>
  
</head>

<body>

    <div>这个默认会被清掉</div>
    <div id='example'></div>
    <pre>
      
    </pre>

    <script type='text/babel'>
    var container = document.getElementById("example")
    var div = container
   var expect = function(a) {
      return {
          toBe: function(b) {
              console.log(a,"\nvs\n", b, a === b)
          }
      }
  }
 

var list = [];
var flag = 1
 function logger(e){
   console.log(e)
 }
 var parentIntance 
 class Page extends React.Component{
     constructor(props){
        super(props)
        this.state = {
            a: 111,
            b: 222,
            c: 333
        }
        parentIntance = this
     }
     render(){
         console.log("Page.render()")
         return <div>
            <A  name="a" text={this.state.a} />
            <A  name="b" text={this.state.b} />
            <A  name="c" text={this.state.c} />
            </div>
     }
 }
 class A extends React.Component {
     constructor(props) {
         super(props);
         this.state = {
             text: props.text
         };
     }

     componentDidMount() {
         logger(this.props.name + " did mount");
         if(this.props.name === "a"){
             console.log("父组件更新")
            parentIntance.setState({
                a: 444
            })
         }
      //   ReactDOM.render(<div>{this.state.text}</div>, div);
     
     }
     componentWillReceiveProps(nextProps){
        logger(this.props.name + " will receive "+nextProps.text +" "+ this.props.text);
        if(nextProps.text !== this.props.text){
            this.setState({
                text: nextProps.text
            })
        }

     }
     componentDidUpdate() {
        logger(this.props.name + " did update");
     }
     render() {
         return <div className={this.props.name}>{this.state.text}</div>;
     }
 }
 
 var s = ReactDOM.render(<Page />, div);