步骤七:Redux封装【React项目创建】

355 阅读1分钟

严格意义来说,不应该叫封装,而是应用

对我个人来说,我喜欢使用redux-thunk中间件。我个人比较排斥redux-saga。如果观点不同,请轻喷

  • 全局唯一的store
// store.ts
import { createStore, compose, appliMiddleware, combineReducers } from "redux";
import thunk from "redux-thunk";
import reducer1, { State1 } from "./reducers/reducer1";
import reducer2, { State2 } from "./reducers/reducer2";

export interface Store {
    state1: State1,
    state2: State2
}

const reducer = combineReducers({
    state1: reducer1,
    state2: reducer2,
})

const middlewares = [thunk]; // 中间件

const storeEnhancers = compose(
    applyMiddleware(...middlewares),
    window?.devToolsExtension(), // chrome插件使用
)

const store = createStore(reducer, storeEnhancers)
export default store;
  • 不同功能数据对应不同的reducer
// reducers/reducer1/reducer.ts
// 定义reducer
export const initState = {
    key: ""
}

export type State1 = typeof initState;

export default (state = initState, action: AnyAction): State1 => {
    switch(action.type) {
        case ""
            return { ...state, key:action.payload }
        default:
            return state;
    }
}
// reducers/reducer1/action.ts
// 定义action
const action = {
    login(): any {
        return async (dispatch: Dispatch<string>) => {
            try {
                const res = await provider.login(11, 3);
            }
        }
    }
}

消费

消费方式有多种

  • 类组件
import { connect } from "react-redux"
class App extends React.PureComponent {
    // 巴拉巴拉
}

function mstp = (state: Store) => ({ isLogin: state.state1.isLogin })

export default connect(mstp, action)(App)
  • 函数组件
function App() {
    const { isLogin } = useSelector(state => state.state1) // 消费数据
    const dispatch = useDispatch();
    dispatch(actions.login()) // 产生副作用
}

总结

Redux的使用,不是理论知识,没有涉及到实现原理,又是Action、又是Store这些。

另外遇到一个问题,一直没有解决,可以看到action.ts里面的login函数,返回的是any。这是因为ts对Redux的支持不是很好。也可能是我太菜了。欢迎讨论

传送门