Home > Web Front-end > JS Tutorial > body text

How React distinguishes components defined by Class and function

coldplay.xixi
Release: 2020-12-17 10:07:38
Original
2318 people have browsed it

React distinguishes components defined by Class and function: 1. Use function to define components, and add hooks to allow components defined by function to have local state; 2. Use class to define components, and filter out the second parameter of qs prefix.

How React distinguishes components defined by Class and function

The operating environment of this tutorial: Windows 7 system, React version 16.8. This method is suitable for all brands of computers.

Related learning recommendations: react video tutorial

React distinguishes the component methods defined by Class and function:

Use function to define components

import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
import qs from "qs"; //qs用来格式化数据
import { movieDetail } from "../../services/movies";
 
//推荐使用function定义组件,react16.8以后新增hook可以让function定义的组件具有局部state
 
export default function Detail() {
  //function定义的组件没有局部的数据,所以使用useState()获取局部数据(局部状态)
  //以下例子第一个参数表示定义的数据,第二个参数表示更改此数据要用到的方法,useState()中的参数表示定义数据的初始值
  //也就是movie={video:{}} 若要定义多个值,多次使用useState就行了
  const [movie, setMovie] = useState({
    video: {},
  });
  const [live, sertLive] = useState({}); //live={}
  //function定义的组件不能使用this.props.location来获取地址栏信息,使用useLocation()获取地址栏信息
  const location = useLocation();
  console.log(location);
 
  //function定义的组件也没有生命周期的钩子函数,我们使用useEffect来模拟生命周期,
  //参数一表示参数二依赖的内容发生改变之后触发的回调函数,如果参数二为空数组表示只执行一次(初始化执行)
  useEffect(() => {
    const query = qs.parse(location.search, {
      ignoreQueryPrefix: true, //此参数表示过滤掉前缀
    });
    //useEffect中调用异步函数如下所示
    async function fetchData() {
      // You can await here
      const result = await movieDetail(query.id);
      console.log(result);
      setMovie(result.data.data.basic);
      sertLive(result.data.data.live);
    }
    fetchData();
  }, []);
  return (
    <div>
      <img
        style={{ width: "100%", margin: "0 auto", display: "block" }}
        src={live.img}
      ></img>
      <h1>{movie.name}</h1>
      <p>{movie.story}</p>
      <video controls autoPlay src={movie.video.url}></video>
    </div>
  );
}
Copy after login

Use class to define components

import React, { useState, useEffect, Component} from "react";
import { useLocation } from "react-router-dom";
import qs from "qs"; //qs用来格式化数据
import { movieDetail } from "../../services/movies";
 
//使用class定义组件中this指向复杂,不推荐使用
 
export default class Detail extends Component {
  constructor(props) {
    super(props);
    console.log(props);
    this.state = {
      movie: {
        video: {
          url: "",
        },
      },
    };
  }
  async componentDidMount() {
    console.log(this.props.location.search); //url传参
    //qs第二个参数表示过滤掉前缀
    const query = qs.parse(this.props.location.search, {
      ignoreQueryPrefix: true,
    });
    console.log(query);
    const result = await movieDetail(query.id);
    console.log(result);
    this.setState({
      movie: result.data.data.basic,
    });
    document
      .querySelectorAll(".nav ul li")[1]
      .querySelector("a")
      .classList.add("active");
  }
  componentWillUnmount() {
    document
      .querySelectorAll(".nav ul li")[1]
      .querySelector("a")
      .classList.remove("active");
  }
  render() {
    return (
      <div>
        <h1>{this.state.movie.name}</h1>
        <p>{this.state.movie.story}</p>
        <video controls autoPlay src={this.state.movie.video.url}></video>
      </div>
    );
  }
}
Copy after login

Related learning recommendations: javascript video tutorial

The above is the detailed content of How React distinguishes components defined by Class and function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template