react props与stat

1. props

默认 Props

你可以通过组件类的 defaultProps 属性为 props 设置默认值,实例如下:

React 实例

class HelloMessage extends React.Component {

  render() {

    return (

      <h1>Hello, {this.props.name}</h1>

    );

  }

}

HelloMessage.defaultProps = {

  name: 'Runoob'

};

const element = <HelloMessage/>;

ReactDOM.render(

  element,

  document.getElementById('example')

);

 

2. State与生命周期

应用程序的 UI 是动态的,并会伴随着时间的推移而变化。state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。

React 把组件看成是一个状态机(State Machines)。通过与用户的交互,实现不同状态,然后渲染 UI,让用户界面和数据保持一致。React 里,只需更新组件的 state,然后根据新的 state 重新渲染用户界面(不要操作 DOM)。

(1)向class组件中添加局部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>

    );

  }

}


ReactDOM.render(

  <Clock />,

  document.getElementById('root')

);

(2)挂载与卸载(构造与析构),将生命周期方法添加到 Class 中

class Clock extends React.Component {

   constructor(props) {

    super(props);

    this.state = {date: new Date()};

  }

  componentDidMount() {

    this.timerID = setInterval(

      () => this.tick(),

      1000

    );

  }

  componentWillUnmount() {

    clearInterval(this.timerID);

  }

  tick() {

    this.setState({

      date: new Date()

    });

  }

  render() {

    return (

      <div>

        <h1>Hello, world!</h1>

        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>

      </div>

    );

  }

}

ReactDOM.render(

  <Clock />,

  document.getElementById('root')

);

(3)正确使用state

(a)不要直接修改state

        此代码不会重新渲染组件:this.state.comment = 'Hello'; 应该使用setState():this.setState({comment: 'Hello'}); 构造函数是唯一可以给this.state赋值的地方。

(2)state的更新可能是异步的

        因为 this.props 和 this.state 可能会异步更新,所以不要依赖他们的值来更新下一个状态。例如,此代码可能会无法更新计数器:

this.setState({

  counter: this.state.counter + this.props.increment,

});

        可以让 setState() 接收一个函数而不是一个对象。这个函数用上一个 state 作为第一个参数,将此次更新被应用时的 props 做为第二个参数:

this.setState((state, props) => ({

  counter: state.counter + props.increment

}));

        上面使用了箭头函数,不过使用普通的函数也同样可以:

this.setState(function(state, props) {

  return {

    counter: state.counter + props.increment

  };

});

(3)state的更新会被合并

        当你调用 setState() 的时候,React 会把你提供的对象合并到当前的 state。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章