React 16.8前后写法差异

return JSX

  • a functional component is a function that returns JSX
import React from "react";
 
const FunctionalComponent = () => {
 return <h1>Hello, world</h1>;
};
  • class component
import React, { Component } from "react";
 
class ClassComponent extends Component {
 render() {
   return <h1>Hello, world</h1>;
 }
}

Handling state

  • functional components
const FunctionalComponent = () => {
 const [count, setCount] = React.useState(0);
 
 return (
   <div>
     <p>count: {count}</p>
     <button onClick={() => setCount(count + 1)}>Click</button>
   </div>
 );
};
  • class components
class ClassComponent extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     count: 0
   };
 }
 
 render() {
   return (
     <div>
       <p>count: {this.state.count} times</p>
       <button onClick={() => this.setState({ count: this.state.count + 1 })}>
         Click
       </button>
     </div>
   );
 }
}

如何保存state以及重置state

preserving and reset state