react

由于react渲染是同步的,如果要在接口请求完数据以后在渲染数据,

componentWillMount --》render-->componentDidMount-->render

react父子组件通信

父传子:props

子传父:setState

如要避免不必要的子组件的重渲染,你需要在所有可能的地方使用 PureComponent,或是手动实现 shouldComponentUpdate 方法。同时你可能会需要使用不可变的数据结构来使得你的组件更容易被优化。

react生命周期

react严格定义了组件的生命周期,生命周期可能会经历如下三个过程:

装载过程(Mount):把组件第一次在dom树中渲染的过程

  constructor

  getInitialState

  getDefaultProps

  componentWillMount

  render

  componentDidMount

更新过程(Update):当组件被重新渲染的过程

  componentWillReceiveProps

  shouldComponentUpdate

  componentWillUpdate

  render

  componentDidUpdate

卸载过程(Unmount):组件从Dom中删除的过程

  componentWillUnmount:工作与componentDidMount有关,比如,在componentDidMount中用非react的方法创造了一些dom元素,如果撒手不管可能会造成内存泄漏,那么就需要在componentWillUnmount清理掉

react:子组件向父组件传值

/***实现在输入框输入邮箱时,在div中即时显示输入内容***/


<body>
    <div id="test"></div>
</body>

//子组件
var Child = React.createClass({
    render: function(){
        return (
            <div>
                邮箱:<input onChange={this.props.handleEmail}/>
            </div>
        )
    }
});

//父组件
var Parent = React.createClass({
    getInitialState: function(){
        return {
            email: ''
        }
    },
    handleEmail: function(event){
        this.setState({email: event.target.value});
    },
    render: function(){
        return (
            <div>
                <div>邮箱:{this.state.email}</div>
                <Child name="email" handleEmail={this.handleEmail.bind(this)}/>
            </div>
        )
    }
});
React.render(
  <Parent />,
  document.getElementById('test')
);

  

原文地址:https://www.cnblogs.com/afterwawa/p/8687562.html