Table of Contents
Install Redux
yarn add react-redux redux
yarn add --dev @types/react-redux @types/redux
Define Redux
Define Actions
- 用描述性的方式告诉store应该如何处理数据;
- Action Creator用来创造Actions(code reuse);
export const selectSong = (song: any) => { return { type: 'SONG_SELECTED', payload: song } };
Define Reducers
- 定义reducers: 定义数据的
初始状态
和处理方法
export const songsReducer = () => {
return [
{ title: 'No Scrubs', duration: '4:05' },
{ title: 'Macarena', duration: '2:30' },
{ title: 'All Star', duration: '3:15' },
{ title: 'I want it That Way', duration: '5:10' }
];
};
export const selectedSongsReducer = (selectedSong = null, action: { type: string, payload: any }) => {
if (action.type === 'SONG_SELECTED') {
return action.payload;
}
return selectedSong;
};
// components/reducers/index
import { combineReducers } from 'redux';
import { selectedSongsReducer, songsReducer } from './Song'
export default combineReducers({
songs: songsReducer,
selectedSong: selectedSongsReducer
});
Define Store
import { createStore } from "redux";
import reducer from './reducers';
const store = createStore(reducer);
export default store;
Use Redux
Read data
import { useSelector } from 'react-redux';
const selectedSong = useSelector(state => _.get(state, ['selectedSong'], null));
Send data
const dispatch = useDispatch();
<button className="ui button primary"
onClick={() => dispatch(selectSong(song))}> Select </button>
Others
useReducer
- 并不是
redux
的一部分
- 是用来聚合某些相互依赖的状态用的,局部
状态管理器
- 在
functional component
的情景下,能够callback function
读取到最新的数据
,而不是snapshot
的数据
useReducer
跟useState
一样,每次状态变化都会引起组件的重新渲染
- 引起状态变化的组件和存储状态的组件不是同一个,能够避免不必要的更新
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const [data, setData] = useState({});
const reducer = (prevState, action) => {
switch(action.type){
case 'a': return {...state};
case 'b': return {...state, x:1};
case 'c': return {...state, x:2};
default: throw new Error();
}
}
const [state, dispatch] = useReducer(reducer, {
isLoading: false,
isError: false,
data: {}
})
Reference
Question
- Why we need to use
useReducer()
and useCallback()
?
- Class Component vs Functional Component? Answer