[标准]state生命周期,react动态加载显示交互

zhuanbike 2021-12-26 705

import React from "react";
import ReactDOM from "react-dom";
const todoList = ["张三", "李四", "王五", "孙六"];
class Todo extends React.Component {
  render() {
    return <li>您好, {this.props.content}</li>;
  }
}
class App extends React.Component {
  constructor(props) {// React 约定每个继承自 React.Component 的组件在定义 constructor 方法时,要在方法内首行加入 super(props) 
    super(props);
    this.state = {
      todoList: []
    };//初始化
  }
  componentDidMount() {//挂载state
    this.timer = setTimeout(() => {//设置计时器,这个硬性记忆吧,记不住回来照着笔记打
      this.setState({
        todoList: todoList//this.setState更新state
      });
    }, 2000);//2秒后生效
  }
  componentWillUnmount() {
    clearTimeout(this.timer);//计时器超时后卸载states生命周期
  }
  render() {//渲染输出
    return (
      <ul>
        <Todo content={this.state.todoList[0]} />
        <Todo content={this.state.todoList[1]} />
        <Todo content={this.state.todoList[2]} />
        <Todo content={this.state.todoList[3]} />
      </ul>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));


最新回复 (0)
发新帖