React Hooks是什么请自行搜索,一搜一大片,不再赘述~
一切以实战经验出发,话不多说,三个文件:index.js / state.js / reduce.js
// index.js
import React, {useState, useEffect} from 'react'
import ReactDOM from "react-dom";
import State from "./state";
import Reduce from "./reduce";
class App extends React.Component {
render(){
return (
<div className="App">
<h1>React Hooks - useState</h1>
<State/>
<h1>React Hooks - useReduce</h1>
<Reduce/>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
// state.js
import React, {useState, useEffect} from 'react'
export default function () {
const [count, setCount] = useState(0);
const [list, setList] = useState([]);
const [loading, setLoading] = useState(false);
// 计算器 - 加
function inCount() {
setCount(count + 1)
}
// 计算器 - 减
function deCount() {
setCount(count - 1)
}
// 模拟数据
function getApi(n) {
return new Promise((resolve, reject) => {
if (n) {
resolve({code: 200, data: [{label: '姓名', value: '张三'}]});
} else {
reject({code: 500, data: []});
}
});
}
// 相当于class组件中的:componentDidMount/componentDidUpdate
useEffect(() => {
// count
console.log('count', count);
// list
if (loading) {
getApi(1).then(async res => {
console.log(res.data);
await setList(res.data);
await setLoading(false);
})
}
}, [count, loading]);
return (
<div>
<hr/>
<div>
<button onClick={inCount}>+</button>
<button>{count}</button>
<button onClick={deCount}>-</button>
</div>
<hr/>
<div>
{list.map((d, i) => (<p key={i}>{d.label} - {d.value}</p>))}
<button onClick={() => setLoading(true)}>获取数据</button>
</div>
<hr/>
</div>
)
}
// reducer.js
import React, {useState, useReducer, useEffect} from 'react'
export default function () {
const initialState = {
count: 0,
list: [],
};
function myReducer(state, action) {
// console.log(action);
switch (action.type) {
case 'increase':
return {
...state,
count: action.count,
};
case 'decrease':
return {
...state,
count: action.count,
};
case 'list':
return {
...state,
list: action.list,
};
default:
return state;
}
}
const [state, dispach] = useReducer(myReducer, initialState);
const [loading, setLoading] = useState(false);
// 计算器 - 加
function inCount() {
dispach({type: 'increase', count: state.count + 1});
}
// 计算器 - 减
function deCount() {
dispach({type: 'decrease', count: state.count - 1});
}
// 模拟数据
function getApi(n) {
return new Promise((resolve, reject) => {
if (n) {
resolve({code: 200, data: [{label: '姓名', value: '李四'}]});
} else {
reject({code: 500, data: []});
}
});
}
useEffect(() => {
// count
console.log('count', state);
// list
if (loading) {
getApi(1).then(async res => {
console.log(res.data);
await dispach({type: 'list', list: res.data});
await setLoading(false);
})
}
}, [state, loading]);
return (
<div>
<hr/>
<div>
<button onClick={inCount}>+</button>
<button>{state.count}</button>
<button onClick={deCount}>-</button>
</div>
<hr/>
<div>
{state.list.map((d, i) => (<p key={i}>{d.label} - {d.value}</p>))}
<button onClick={() => setLoading(true)}>获取数据</button>
</div>
<hr/>
</div>
)
}