react创建项目学习基础语法(二)

import React, { Component } from 'react'
import logo from './logo.svg';
import './App.css';
import axios from 'axios' // react 使用 axios

// 本页面只做基础的 react 常用语法糖
export default class App extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      name: '波波',
      age: 20,
      date: new Date(),
      isShow: false,
      list: [{id: 1, name: 'react'}, {id: 2, name: 'vue'}],
      value: ''
    }
  }
  // componentWillMount和componentDidMount这两个生命周期函数,只在页面刷新时执行一次,而render函数是只要有state和props变化就会执行
  //  React16新的生命周期弃用了componentWillMount、componentWillReceivePorps,componentWillUpdate
  // 新增了getDerivedStateFromProps、getSnapshotBeforeUpdate来代替弃用的三个钩子函数(componentWillMount、componentWillReceivePorps,componentWillUpdate)
  // React16并没有删除这三个钩子函数,但是不能和新增的钩子函数 17版本将会删除(componentWillMount、componentWillReceivePorps,componentWillUpdate)
  componentWillMount(){
    console.log('componentWillMount----组件将要挂载到页面---1')
  }
  
  // 建议在componentDidMount函数里作ajax请求
  componentDidMount() {
    this.timer = setInterval(() => {
      this.setState({
        date: new Date()
      })
    }, 1000);
    console.log('componentDidMount---组件挂载完毕-----3')
    // 在node_modules文件下找到react_script文件夹,代开scripts文件下,找到 starts.js文件 修改默认的3000端口
    // 在package.json 文件 中 配置 "proxy": "http://xxxx/" 代理地址(后端服务器地址) 解决跨域(三种常见方式)
    // webpack 里面配置 devServer 再配置 proxy 或者 使用 http-proxy-middleware 中间件处理
    axios.post('/asset-week-manage/weekly/dept/list').then(
      res => {
      console.log('axios 获取数据成功:'+ JSON.stringify(res))  
      const resdata = res.data.returnData;
      this.setState({
        list: resdata // 动态数据
      })
    }).catch(
      error => {console.log('axios 获取数据失败' + error)
    })
  }

  // nextProps:变化后的属性;
  // nextState:变化后的状态  
  shouldComponentUpdate(nextProps,nextState){
    console.log('shouldComponentUpdate---组件发生改变前执行--它要求返回一个布尔类型的结果,必须有返回值,这里就直接返回一个true了(真实开发中,视情况而定做相关处理)---4')
    // if(nextProps.content !== this.props.content){
    //   return true
    // }else{
    //   return false
    // }
    return true
  }

  //shouldComponentUpdate返回true才会被执行。
  componentWillUpdate(){
    console.log('componentWillUpdate---组件更新前,shouldComponentUpdate函数之后执行-------5')
  }

  // 简单的说就是 触发了第二次render之后执行
  componentDidUpdate(){
    console.log('componentDidUpdate----组件更新之后执行----6')
  }

  // 这时候会发现函数什么时候都不会被执行 凡是组件都有生命周期函数,所以子组件也是有的,并且子组件接收了props,这时候函数就可以被执行了(把这个挪到子组件测试)
  // 子组件接收到父组件传递过来的参数,父组件render函数重新被执行,这个生命周期就会被执行。
  // 也就是说这个组件第一次存在于Dom中,函数是不会被执行的;
  // 如果已经存在于Dom中,函数才会被执行。
  componentWillReceiveProps(){
    console.log('componentWillReceiveProps-----子组件接收props调用触发')
  }

  componentWillUnmount(){
    clearInterval(this.timer)
    console.log('componentWillUnmount---组件卸载')
  }

  // 渲染函数 
  render() {
    console.log('render---组件挂载中---2')
    const { age, isShow } = this.state;
    // console.log( age, isShow);
    return (
      <div className="wrap-box">
        {/* 属性 xx={} 形式使用 
        类名 classsName 添加  
        组件名称必须以大写字母开头
        React 会将以小写字母开头的组件视为原生 DOM 标签 
        所有 React 组件都必须像纯函数一样保护它们的 props 不被更改 
        不要直接修改 State
        自上而下”或是“单向”的数据流
        class 的方法默认不会绑定 this 方法调用需要bind(this) 或者使用 箭头函数
        true && expression 总是会返回 expression, 而 false && expression 总是会返回 false
        阻止组件渲染  render 方法直接返回 null,而不进行任何渲染 在组件的 render 方法中返回 null 并不会影响组件的生命周期
        key 只是在兄弟节点之间必须唯一 在 map() 方法中的元素需要设置 key 属性
        如果你不希望最外层用div包裹着 可以使用 Fragment 标签 (例如使用 flex写样式时候)
        */}
        <p>直接使用setState里面的值---{this.state.name}</p>
        <p>ES6解构使用setState里面的值---{age}</p>
        <p>时间方法:{this.state.date.toLocaleTimeString()}</p>
        <p>判断条件渲染----{isShow ? 'ture显示左边' : 'false显示右边'}</p>
        <img src={logo} className="App-logo" alt="logo" />
        <ul>
          {
           this.state.list.map((item,index) => {
              return (
                <li key={item.id.toString()}>
                  {item.name}---{index}
                </li>
              )}
            )
          }
        </ul>
        {/* 表单提交 */}
        <form onSubmit={this.handleSubmit}>
          <label>
            名字:
            <input type="text" value={this.state.value} onChange={this.handleChange} />
          </label>
          <input type="submit" value="提交" />
        </form>
        <button onClick={this.handleClick.bind(this)}> Click me </button>
        <button onClick={this.handleClick1}> Click me </button>
      </div>
    )
  }

  // 各类方法
  handleClick() {
    alert('方式1')
    // 如果不绑定 this 则打印出 this 为 undefined
    console.log('this is:', this);
  }

  handleClick1 = () => {
    alert('方式2')
    //箭头函数自动绑定this
    console.log('this is:', this);
  }
  // 绑定输入框值
  handleChange = (event) => {
    this.setState({value: event.target.value});
  }
  // 提交
  handleSubmit = (event) => {
    alert('提交的名字: ' + this.state.value);
    event.preventDefault();
  }
}

// function App() {
//   return (
//     <div className="App">
//       <header className="App-header">
//         <img src={logo} className="App-logo" alt="logo" />
//         <p>
//           Edit <code>src/App.js</code> and save to reload.
//         </p>
//         <a
//           className="App-link"
//           href="https://reactjs.org"
//           target="_blank"
//           rel="noopener noreferrer"
//         >
//           Learn React
//         </a>
//       </header>
//     </div>
//   );
// }

// export default App;

以上为react最简单基础的语法糖;更多参照官方网站自己另外拓展中~以上用APP组件作为测试组件;

猜你喜欢

转载自www.cnblogs.com/lhl66/p/12461508.html