本文主要是介绍react-redux搭建及不同版本间的对比,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.经典版
1. 安装Redux和React Redux
npm install redux react-redux
2. 创建action
// actions/counterActions.js
export const increment = () => {return {type: 'INCREMENT'};
};export const decrement = () => {return {type: 'DECREMENT'};
};export const add = (amount) => ({type: 'ADD',payload: amount,
});
3. 创建reduce
// reducers/counterReducer.js
const counterReducer = (state = 0, action: any) => {switch (action.type) {case 'INCREMENT':return state + 1;case 'DECREMENT':return state - 1;case "ADD":return state + 5;default:return state;}
};export default counterReducer;
4. 在项目的src目录中创建store.js
// store.js
import { legacy_createStore as createStore, combineReducers, applyMiddleware, compose } from 'redux';// 引入 reducer
import counterReducer from './reducer';// 使用 combineReducers 组合多个 reducer
const rootReducer = combineReducers({counter: counterReducer,// 这里可以添加更多的 reducer
});// 为 Redux DevTools 扩展设置
const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;// 创建 Redux store,添加中间件支持,同时启用 Redux DevTools
const store = createStore(rootReducer,/* preloadedState, */composeEnhancers(applyMiddleware(// 这里是将来可能添加的中间件))
);export default store;
5. 在React组件中使用
a. 首先,在应用的
这篇关于react-redux搭建及不同版本间的对比的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!