ReactDOM.render

React元素是不可变的,一旦创建了就不可以更新,我们通过ReactDOM.render创建组件,那我们也可以通过重新调用该方法来实现UI更新的效果

  1. function Clock(props) {
  2. return (
  3. <div>
  4. <h1>Hello, world!</h1>
  5. <h2>It is {props.date.toLocaleTimeString()}.</h2>
  6. </div>
  7. );
  8. }
  9. function tick() {
  10. ReactDOM.render(
  11. <Clock date={new Date()} />,
  12. document.getElementById('root')
  13. );
  14. }
  15. setInterval(tick, 1000);

class组件也是如此,只不过是把函数组件修改成class的写法了,注意这个地方,props修改为this.props,因为class组件继承于React.compnent,所以class组件有生命周期函数,当然,后期,函数式组件也具有了生命周期,供组件使用state

  1. class Clock extends React.Component {
  2. render() {
  3. return (
  4. <div>
  5. <h1>Hello, world!</h1>
  6. <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
  7. </div>
  8. );
  9. }
  10. }
  11. function tick() {
  12. ReactDOM.render(
  13. <Clock date={new Date()} />,
  14. document.getElementById('root')
  15. );
  16. }
  17. setInterval(tick, 1000);

state更新UI

通过生命周期来设置定时器,然后通过setState来动态改变UI里面的值

  1. import React from 'react';
  2. class App extends React.Component{
  3. constructor(props) {
  4. super(props)
  5. this.state = {
  6. date: new Date()
  7. }
  8. }
  9. componentDidMount() {
  10. this.timer = setInterval(() => {
  11. this.tick()
  12. }, 1000)
  13. }
  14. tick() {
  15. this.setState({
  16. date: new Date()
  17. })
  18. }
  19. componentWillUnmount() {
  20. clearInterval(this.timer)
  21. }
  22. render() {
  23. return (
  24. <div>
  25. <h1>hello world</h1>
  26. <h2>it is now:{this.state.date.toLocaleTimeString()}</h2>
  27. </div>
  28. )
  29. }
  30. }
  31. export default App;

注意

  1. 不要直接修改state

    1. // 错误
    2. this.state.date = 'new Value'
    3. // 正确
    4. this.setState({
    5. date: 'new Value'
    6. })
  2. state更新可能是异步的(因为出于性能考虑,React 可能会把多个 setState() 调用合并成一个调用)

    1. // Wrong
    2. this.setState({
    3. counter: this.state.counter + this.props.increment,
    4. });
    5. // Correct---箭头函数
    6. this.setState((state, props) => ({
    7. counter: state.counter + props.increment
    8. }));
    9. // Correct
    10. this.setState(function(state, props) {
    11. return {
    12. counter: state.counter + props.increment
    13. };
    14. });
  3. state更新可以合并