1. 有状态组件的写法对比
1.原始写法
import React, { Component } from 'react';
class Example extends Component {
constructor(props) {
super(props);
this.state = { count: 0 }
}
render() {
return (
<div>
<p>你点击了{this.state.count} 秒</p>
<button onClick={this.addCount.bind(this)}>点击</button>
</div>
);
}
addCount() {
this.setState({ count: this.state.count + 1})
}
}
export default Example;
2.React Hooks写法
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0)
return (
<div>
<p>你点击了{count} 秒</p>
<button onClick={() => {setCount(count + 1)}}>点击</button>
</div>
)
}
export default Example;
注释:const [count, setCount] = useState(0)
Count为参数setCount为刷新参数的方法useState(0):初始值为0
初始值为对象:例子:{val:1}
const [count2, setcount2] = useState({'val': 1})
使用:{count2.val}
修改:setcount2({ val: count2.val + 1 })
2.useEffect
你可以把useEffect Hook 看做componentDidMount,componentDidUpdate函数的组合。(初始化或页面刷新的时候会触发)
import React, { useState, useEffect } from 'react';
function Example() {
const [form, setValues] = useState({
username: 'username',password: 'password'
});
const [count2, setcount2] = useState({'val': 22 })
useEffect(() => {
console.log(`${JSON.stringify(form)}${JSON.stringify(count2)}`) })
const printValues = e => {
e.preventDefault();
console.log(form.username, form.password);
};
const updateField = e => {
setValues({ ...form,[e.target.name]: e.target.value });
};
return (
<div>
<p>{form.username}-{form.password}</p>
<p>{count2.val}</p>
<button onClick={() => { setcount2({ val: count2.val + 1 }) }}>点击</button>
<form onSubmit={printValues}>
<label> Username:
<input
value={form.username}
name="username"
onChange={updateField}
/>
</label>
<label> Password:
<input
value={form.password}
name="password"
type="password"
onChange={updateField}
/>
</label>
</form>
</div>
)
}
export default Example;
返回一个函数的形式可以进行解绑
例如此处的:
useEffect(() => {
console.log(`${JSON.stringify(form)}${JSON.stringify(count2)}`),
return ()=>{
console.log('解绑!')
}
})
弊端:这样每次状态发生变化,useEffect都进行了解绑。
使用useEffect 的第二个参数 [ ]为空表示只有被销毁才被执行
useEffect(()=>{
console.log(`${JSON.stringify(form)}${JSON.stringify(count2)}`),
return ()=>{
console.log('解绑了!Index页面')
}
},[])
设置参数此处为count发生变化就解绑
useEffect(()=>{
console.log(`useEffect=>You clicked ${count} times`)
return ()=>{
console.log('====================')
}
},[count])
3.useContext父子传值
import React, { useState, createContext, useContext } from 'react';
const CountContext = createContext(); // 1声明一个createContext
//父组件
function Example3() {
const [count, setCount] = useState(0) //2.使用useState设置一个参数
return (
<div>
<p>你点击了{count} 秒</p>
<button onClick={() => { setCount(count + 1) }}>点击</button>
//3.使用声明的createContext通过Provider 传递value
<CountContext.Provider value={count}>
<Child></Child> //4.引入子组件
</CountContext.Provider>
</div>
)
}
//子组件
function Child() {
let count = useContext(CountContext)//5.接收到父组件的值
return (
<h2>子组件接收:{count}</h2>
)
}
export default Example3;
4.useReducer
import React, { useReducer } from 'react';
function UseReducerDemo() {
const [count, dispatch] = useReducer((state, action) => {
switch (action) {
case 'add':
return state + 1
case 'sub':
return state - 1
default:
return state
}
}, 0)
return (
<div>
<h2>当前:{count}</h2>
<button onClick={() => { dispatch('add') }}>点击</button>
<button onClick={() => { dispatch('sub') }}>点击</button>
</div>
)
}
export default UseReducerDemo
注释:useReducer((状态,逻辑的判断参数)=>{},‘初始值’)
const [count, dispatch] = useReducer()
// useReducer()会返回count,dispatch派发action方法