主题
redux 与 hooks
准备
引入包
shellnpm install redux react-redux --save
创建 store 仓库:
src/store/index.js
jsimport { createStore } from 'redux' import reducer from './reducer' export default createStore(reducer) // 把下面的记录本内容传给store
创建 store 的记事本:
src/store/reducer.js
tsimport { Reducer } from 'redux/index' export interface StoreProps { // store 的类型 } const defalutStore: StoreProps = { // 默认数据 } const reducer: Reducer<StoreProps> = (state = defalutStore, action) => { switch (action.type) { default: return state } } export default reducer
在
App.js
中使用Provider
包裹jsximport {Provider} from 'react-redux' import store from './store' function App () { return ( <div className="App"> <Provider store={store}> </Provider> </div> ) }
使用
commit
jsimport { useDispatch } from 'react-redux' const dispatch = useDispatch() dispatch(action)
获取数据
jsimport { useSelector } from 'react-redux' import { StoreProps } from '../../store/reducer' const user = useSelector<StoreProps>(state => state.user)