yarn add react-redux redux
yarn add --dev @types/react-redux @types/redux
- 用描述性的方式告诉store应该如何处理数据;
- Action Creator用来创造Actions(code reuse);
export const selectSong = (song: any) => { return { type: 'SONG_SELECTED', payload: song } };
- 定义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
});
import { createStore } from "redux";
import reducer from './reducers';
const store = createStore(reducer);
export default store;
import { useSelector } from 'react-redux';
const selectedSong = useSelector(state => _.get(state, ['selectedSong'], null));
const dispatch = useDispatch();
<button className="ui button primary"
onClick={() => dispatch(selectSong(song))}> Select </button>
- 并不是
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: {}
})
- Why we need to use
useReducer()
and useCallback()
?
- Class Component vs Functional Component? Answer