1. react-redux 之 Hooks api
1.1 useState 的缺点
useState
可以用最简单的方式更新状态,但是状态更新的逻辑(例如上面例子中的加减一运算)散落在业务代码中,不能独立复用,也不便于测试。
import React, { useState } from "react";
const ComponentUseState = () => {
const [num, setNum] = useState(0);
return (
<div>
<h2>Using useState</h2>
Number: {num}
<button onClick={() => setNum(num + 1)}>+</button>
<button onClick={() => setNum(num - 1)}>-</button>
</div>
);
};
1.2 【进化】useReducer 解决 useState 无法解决的问题
import React, { useReducer } from 'react'
const initialState = {num: 0};
const reducer = (state, action) => {
switch(action.type) {
case 'decrement':
return {...state, num: state.num - 1}
case 'increment':
return {...state, num: state.num + 1}
default:
return state;
}
}
const ComponentUseReducer = () => {
const [state, dispatch] = useReducer(reducer, initialState)
const { num } = state
return (
<div>
<h2>Using useReducer</h2>
Number: {num}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</div>
);
};
export default ComponentUseReducer;
1.2.1 useReducer 无法像redux 跨组件状态共享
1.3 useSelector、useDispatch
import React from "react";
import { createStore } from "redux";
import { Provider, useSelector, useDispatch } from "react-redux";
const initialState = { num: 0 };
const reducer = (state, action) => {
switch (action.type) {
case "decrement":
return { ...state, num: state.num - 1 };
case "increment":
return { ...state, num: state.num + 1 };
default:
return state;
}
};
const store = createStore(reducer, initialState);
const ComponentUseReactRedux = () => {
return (
<div>
<h2>ComponentUseReactRedux</h2>
<Provider store={store}>
<ChildComponentUseReactRedux />
</Provider>
</div>
)
}
const ChildComponentUseReactRedux = () => {
const num = useSelector(state => state.num);
const dispatch = useDispatch();
return (
<div>
<h3>Using useSelector, useDispatch</h3>
Number: {num}
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</div>
);
};
export default ComponentUseReactRedux;
1.3.1 代码说明:
createStore
const store = createStore(reducer, initialState);
再通过Provider向子组件暴露store,通过store在父子组件之间共享状态
<Provider store={store}>
<ChildComponentUseReactRedux />
</Provider>
useSelector
const num = useSelector(state => state.num);
const selector = state => {
return state.num;
}
const num = useSelector(selector);
useDispatch
const dispatch = useDispatch()
const ComponentUseReactRedux = () => {
return (
<div>
<h2>ComponentUseReactRedux</h2>
<Provider store={store}>
<ChildComponentUseReactRedux />
<ChildComponentUseReactRedux />
</Provider>
</div>
)
}
总结 - 进化流
- 【useState】-> 【useReducer】-> 【useSelector、useDispatch】
- 通过useSelector、useDispatch等方法,我们可以用Hooks方法完成Redux的功能,Hooks和Redux之间没有替代关系,应该更好地共存和融合。
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!