React
React grew out of an internal project at Facebook, where the company was unhappy with all the JavaScript MVC frameworks on the market and decided to write one for Instagram. After it was built, it was found to be very useful and opened source in May 2013.
2. React features and advantages
(1) virtual DOM
The way we used to manipulate the DOM was document.getelementById (), which essentially reads the HTML DOM structure, converts it into variables, and then operates on it. Reactjs defines a dom model in the form of variables, all operations and transformations directly in the variables, which reduces the operation of the real DOM and greatly improves performance.
(2) Componentized coding
The core idea of React is to treat any area or element on a page as a component. What is a component? Component refers to the aggregation containing HTML, CSS, JS and image elements at the same time. The core of react development is to split the page into several components, and CSS, JS and image are coupled in the react component at the same time. This mode greatly reuses code, simplifies project coding and improves operation efficiency
(3) Diffing algorithm
React uses Diffing to minimize redraw pages
(4) the JSX syntax
In React, we use the Render function to build the dom structure of the component with high performance because it saves the process of finding and compiling the template. However, when creating the structure with createElement in Render, the code is less readable and more complex. You can solve this problem by using JSX syntax to create the DOM in Render, but only if you need a tool to compile JSX
Write your first React application
Install create-react-app globally
$ npm install -g create-react-app
Copy the code
Create a project
$ create-react-app my-react-project
Copy the code
run
npm start
Copy the code
4. React Basics
1. Two ways to create the virtual Dom
(1) Use JS to create the virtual DOM
Create a virtual DOM
const VDOM = React.createElement('h1', {id:'title'},React.createElement('span', {},'Hello,React'))
//2. Render the virtual DOM to the page
ReactDOM.render(VDOM,document.getElementById('test'))
Copy the code
(2) Use JSX to create virtual DOM
Create a virtual DOM
const VDOM = ( /* Do not write quotes here, because it is not a string */
<h1 id="title">
<span>Hello,React</span>
</h1>
)
//2. Render the virtual DOM to the page
ReactDOM.render(VDOM,document.getElementById('test'))
Copy the code
2. Two ways to create components
(1) Create components functionally
function App () {
return <h1>I was the first React project</h1>
}
ReactDOM.render(<App />.document.getElementById('test'))
/* The first argument to render is
, not App. Performed ReactDOM. Render (< App / >... After that, what happened? 1.React parses the component label and finds the App component. 2. After discovering that the component is defined using a function, call this function to convert the returned virtual DOM into the real DOM and render it on the page. * /
Copy the code
(2) Class create component
class MyComponent extends React.Component {
render(){
//render is placed where? -- on the MyComponent prototype object for instance use.
// Who is this in render? <=> MyComponent instance object.
console.log('this in the render:.this);
return <h2>I am a component defined with a class (for the definition of a complex component)</h2>
}
}
ReactDOM.render(<MyComponent/>.document.getElementById('test'))
/* Execute reactdom.render (
....... After that, what happened? 1.React parses the component tag and finds MyComponent. 2. Discover that the component is defined using a class, then new the instance of that class, and call the render method on the prototype through that instance. 3. Turn the virtual DOM returned by render into the real DOM and render it on the page. * /
Copy the code
3. Three properties of a component instance
State of affairs
(1) Understand that state is the most important attribute of the component object, and the value is the object (which can contain multiple key-value combinations). We can update the state of the component to update the corresponding page display (re-render the component).
(2) Two ways to define state
class Weather extends React.Component{
// Initialization state
state = {isHot:false}
render(){
const {isHot} = this.state
return <h1>The weather isHot today. 'Hot' : 'cool '}</h1>}}Copy the code
class Weather extends React.Component{
constructor(props){
super(props)
// Initialization state
this.state = {isHot:false}}render(){
const {isHot} = this.state
return <h1>The weather isHot today. 'Hot' : 'cool '}</h1>}}Copy the code
SetState takes two arguments. The first argument can be an object, or the method return an object
this.setState({
isLiked:!this.state.isLiked
})
Copy the code
this.setState((prevState, props) = > {
return {
isLiked: !prevState.isLiked
}
})
Copy the code
SetState is asynchronous, so to get the latest state, there is no way to get it, so there is a second argument, which is an optional callback function
this.setState((prevState, props) = > {
return {
isLiked: !prevState.isLiked
}
}, () = > {
console.log('In the callback'.this.state.isLiked)
})
console.log('Outside of setState'.this.state.isLiked)
Copy the code
Props (property)
Properties cannot be changed by the component itself, but you can pass in new props via the parent component’s active re-rendering
(1) Set the default props
class Title extends Component {
static defaultProps = {
name: 'React'
}
render () {
return (
<h1>Welcome to the world of {this.props. Name}</h1>)}}Copy the code
(2), props. Children
class Title extends Component {
render () {
return (
<h1>Welcome to the world of {this.props. Children}</h1>)}}const Content = (props) = > {
return (
<p>{props.children}</p>)}class App extends Component {
render () {
return (
<Fragment>
<Title>React</Title>
<Content><i>React.js</i></Content>
</Fragment>
)
}
}
ReactDOM.render(
<App/>.document.getElementById('root'))Copy the code
Prop-types check React Is designed for building large applications. In a large application, you don’t know what parameters will be passed to the components you write, so the application may not work, but no error will be reported. React provides a mechanism for writing components to check their props. Prop-types need to be installed and used
$ npm i prop-types -S
Copy the code
ref
(1) string form ref
<input ref="input1"/>
// This. Refs.input1
Copy the code
(2) The ref ref attribute in callback form can be set to a callback function, which is officially highly recommended; This function is executed when the component is mounted and the callback function is executed immediately. The callback function takes an instance of the component. The callback is executed immediately when the component is unloaded or the original ref property itself changes, with the callback function parameter null to ensure memory leaks
<input ref={(c) = >{this.input1 = c}}
Copy the code
Refs are created using the property react.createref () and attached to the React element via the ref property. When components are constructed, Refs are typically assigned to instance properties so that they can be referenced throughout the component.
myRef = React.createRef()
<input ref={this.myRef}/>
// this.myRef.current
Copy the code
React event handling
The binding event
Use on+ event name to bind an event. Note that there is a difference between native events, which are all lowercase onclick, and React events, which are humped. React events are not native events, but composite events
Event handler
Write inline arrow functions in Render (not recommended)
Use arrow functions to define a method within a component (recommended)
{handleclick.bind (this)}(not recommended) {onClick={this.handleclick.bind (this)}
Define a non-arrow function method directly within the component and bind(this) from constructor.
class Weather extends React.Component{
constructor(props){
super(props)
// Initialization state
this.state = {isHot:false}
// Fix handleClick's this pointing problem
this.handleClick = this.handleClick.bind(this)}render(){
const {isHot} = this.state
return <h1 onClick={this.handleClick}>The weather isHot today. 'Hot' : 'cool '}</h1>
}
handleClick(){
const isHot = this.state.isHot
this.setState({isHot:! isHot}) } }//2. Render the component to the page
ReactDOM.render(<Weather/>.document.getElementById('test'))
Copy the code
(3) Event parameter transfer
class Login extends React.Component{
// Initialization state
state = {
username:' './ / user name
}
// Save the form data to the state
saveFormData = (dataType) = >{
return (event) = >{
this.setState({[dataType]:event.target.value})
}
}
render(){
return(
<input onChange={this.saveFormData('username')} type="text" name="username"/>)}}// Render component
ReactDOM.render(<Login/>.document.getElementById('test'))
Copy the code
React components pass parameters
(1) Parent component props
(2) Centralized management of sibling message subscription/publication (REDUX)
(3) Centralized message subscription/publishing management (REDUx) conText (Producer-consumer pattern)
Example 1: The son sends a reference to the father
Second, the pubsub
The installation
npm i pubsub-js --save
Copy the code
The introduction of
import PubSub from 'pubsub-js'
Copy the code
use
componentDidMount(){
// Subscribe to the message
this.token = PubSub.subscribe('aaa'.(msg,data) = >{
this.setState(data)
})
}
componentWillUnmount(){
// Unsubscribe
PubSub.unsubscribe(this.token)
}
Copy the code
/ / release
PubSub.publish("aaa", { isLoading: false.users: res.data.items });
Copy the code
6. React lifecycle
Life Cycle Flowchart (old)
Three phases of the life cycle (old)
-
Initialization phase: triggered by reactdom.render () — initial render
1.constructor()
2.componentWillMount()
3.render()
4.componentDidMount()
**2. Update phase: triggered by the component’s internal this.setsate () or the parent’s rerender
1.shouldComponentUpdate()
2.componentWillUpdate()
3.render()
4.componentDidUpdate()
Copy the code
3. Unmount component: componentWillUnmount()
Life Cycle Flowchart (new)
1. Initialization phase: triggered by reactdom.render () — initial render
1.constructor()
2.getDerivedStateFromProps
3.render()
4.componentDidMount()
Copy the code
**2. Update phase: triggered by the component’s internal this.setstate () or the parent’s rerender
1.getDerivedStateFromProps
2.shouldComponentUpdate()
3.render()
4.getSnapshotBeforeUpdate
5.componentDidUpdate()
Copy the code
** 3. Unmount component: componentWillUnmount()
The important hook
- Render: Initialize render or update render call
- ComponentDidMount: Enables listening to send Ajax requests
- ComponentWillUnmount: Do some finishing touches, such as cleaning timers
2.6.6. Hooks to be abandoned
- componentWillMount
- componentWillReceiveProps
- componentWillUpdate
Note: if used now, there will be a warning, which needs to be used with the prefix UNSAFE_. It may be completely abandoned in the future, so it is not recommended to use it
Completion !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!