react基础 props和state,生命周期

2021-02-19  本文已影响0人  肥羊猪
1.props是不可被组件改变的属性,对组件来说是个外部属性。而state是个可改变的状态,用于组件内部。
2.函数组件的props就是函数的入参组件,用于父子之间的传值。
3.state初始化通常在constructor中,通过setState修改后,render()会重新渲染页面。
export default class Item extends React.Component{
  render(){
    return (
      <li>{this.props.item}</li>
    )
  }
}
import Item from "./item";// 父组件
export default class ItemList extends React.Component{
  const itemList = data.map(item => <Item item=item />);
  render(){
    return (
      {itemList}
    )
  }
}
props是一个从外部传进组件的参数,主要作为就是从父组件向子组件传递数据,它具有可读性和不变性,只能通过外部组件主动传入新的props来重新渲染子组件,否则子组件的props以及展现形式不会改变。

一个组件的显示形态可以由数据状态和外部参数所决定,外部参数也就是props,而数据状态就是state。

export default class ItemList extends React.Component{
  constructor(){
    super();
    this.state = {
      itemList:'一些数据',
    }
  }
  render(){
    return (
      {this.state.itemList}
    )
  }
}
注意:通过this.state=来初始化state,使用this.setState来修改state,constructor是唯一能够初始化的地方。
componentDidMount(){
  fetch('url')
    .then(response => response.json())
    .then((data) => {
      this.setState({itemList:item});  
    }
}
export default class ItemList extends React.Component{//setState接受一个对象或者函数作为第一个参数,只需要传入需要更新的部分即可,不需要传入整个对象
  constructor(){
    super();
    this.state = {
      name:'axuebin',
      age:25,
    }
  }
  componentDidMount(){
    this.setState({age:18})  
  }
}
state的主要作用是用于组件保存、控制以及修改自己的状态,它只能在constructor中初始化,它算是组件的私有属性,不可通过外部访问和修改,只能通过组件内部的this.setState来修改,修改state属性会导致组件的重新渲染。

没有state的叫做无状态组件,有state的叫做有状态组件

多用props,少用state。也就是多写无状态组件。

挂载卸载过程
constructor()
componentWillMount()
componentDidMount()
componentWillUnmount ()
更新过程
shouldComponentUpdate(nextProps,nextState)
componentWillUpdate (nextProps,nextState)
componentDidUpdate(prevProps,prevState)
render()

上一篇 下一篇

猜你喜欢

热点阅读