美文网首页
状态与生命周期

状态与生命周期

作者: yanghanbin_it | 来源:发表于2017-06-10 11:53 被阅读0次

将函数组件转换为函数组件

  1. 创建一个同名的类组件并且继承React.Compoent
  2. 添加一个空的方法叫做render()
  3. 把函数里面的内容移到render方法里面
  4. 把render()里面的props替换成this.props
  5. 删掉之前的函数声明的组件
//最后执行第5步,删掉函数声明的组件,这里作为演示,所有不做删除
function Welcome(props){
    return <h1>Hello {1 + props.num}</h1>
}
class Welcome extends React.Component {
    render(){
        <h1>Hello {1 + this.props.num}</h1>
    }
}

state状态

在官网的例子中,当前学到更新UI的方式是重新创建一个element,并render到页面中。在这里将使用state来实现UI更新。
state和props很相似,但state是属于组件私有的属性,并且可以改变的

添加state

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

生命周期

componentDidMount 组件挂载后执行(渲染到dom节点)
componentWillUnmount 组件卸载后执行

正确使用state

  1. 官方建议修改state使用 setState方法 this.setState({comment: 'Hello'});
  2. 唯一声明state仅限在contructor中进行

更新state

更新state是一个异步的过程,如果依赖他们的值来计算下一个state,则可能会出现错误

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

为了解决这个问题,让setState()接收一个函数比接收一个对象的方式更好。

this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

等价于

this.setState(function(prevState, props) {
  return {
    counter: prevState.counter + props.increment
  };
});

单向数据流

在react中无论父组件还是子组件都无法知道其他组件的状态,子组件可以接受父组件传递的数据,父组件可以通过状态选择子组件,这样的自上而下的数据流向,称为单向数据流。

相关文章

网友评论

      本文标题:状态与生命周期

      本文链接:https://www.haomeiwen.com/subject/voufqxtx.html