一.经典版
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. 首先,在应用的最顶层组件(App.js)中使用<Provider>组件包裹你的应用,将store传递给它
// src/App.js
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import MyComponent from './MyComponent';function App() {return (<Provider store={store}><div className="App"><MyComponent /></div></Provider>);
}export default App;
b. 然后,在需要访问Redux store的组件中使用useSelector来读取状态,使用useDispatch来分发action
// Counter.jsx
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement,add } from '../store/action';const Counter = () => {const count = useSelector((state:any) => state.counter);const dispatch = useDispatch();return (<div><h2>Counter: {count}</h2><button onClick={() => dispatch(increment())}>Increment</button><button onClick={() => dispatch(decrement())}>Decrement</button><button onClick={() => dispatch(add(5))}>Add 5</button></div>);
};export default Counter;
二、旧版
这种方法在react-redux版本5及之前非常流行,随着react-redux版本6和7的发布,这种方法已经被淘汰了。但是企业中仍有很多旧项目保持着这种写法,所以学会这项技术的使用也是必须的。
1.安装
npm install redux react-redux
2Action
// src/actions/index.js
export const increment = () => {return {type: 'INCREMENT',};
};export const decrement = () => {return {type: 'DECREMENT',};
};
3.创建Reducer
// src/reducers/counterReducer.js
const counterReducer = (state = { count: 0 }, action) => {switch (action.type) {case 'INCREMENT':return { count: state.count + 1 };case 'DECREMENT':return { count: state.count - 1 };default:return state;}
};export default counterReducer;
4.创建Store
// src/store.js
import { createStore, combineReducers } from 'redux';
import counterReducer from './reducers/counterReducer';const rootReducer = combineReducers({counter: counterReducer,
});const store = createStore(rootReducer);export default store;
5.组件中使用
a. 使用 Provider from react-redux 把 Redux store 提供给 React 应用
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';ReactDOM.render(<Provider store={store}><App /></Provider>,document.getElementById('root')
);
b. 然后,在需要访问Redux store的组件中使用
// src/App.js
import React from 'react';
import { connect } from 'react-redux';
import { increment, decrement } from './actions';// 定义并导出函数式组件
const App = (props) => {return (<div><h2>Counter: {props.count}</h2><button onClick={props.increment}>+</button><button onClick={props.decrement}>-</button></div>);
};// mapStateToProps remains unchanged
const mapStateToProps = (state) => {return {count: state.counter.count,};
};// mapDispatchToProps remains unchanged as well
const mapDispatchToProps = { increment,decrement,
};// 在组件中使用 connect() 去连接 Redux store
export default connect(mapStateToProps, mapDispatchToProps)(App);
三、最新版
@reduxjs/toolkit 是 Redux 团队推荐的方式来编写 Redux 逻辑的工具集。它旨在提供更简便的 API,帮助开发者解决 Redux 应用中经常遇到的一些常见问题,如配置 store、添加中间件、编写 reducer 逻辑等。Redux Toolkit 引入了几个核心概念,如“切片(slices)”来简化 reducer 和 action creators 的编写,以及创建异步逻辑的“createAsyncThunk”等工具。
1.安装
npm install @reduxjs/toolkit react-redux
2.使用 createSlice 创建一个包含了 reducer 函数和 actions 的切片(slice)
// slices/counterSlice.js
import { createSlice } from '@reduxjs/toolkit';export const counterSlice = createSlice({name: 'counter',initialState: { value: 0 },reducers: {increment: state => {state.value += 1;},decrement: state => {state.value -= 1;},add: (state,pa) => {state.value += pa.payload;},},
});export const { increment, decrement,add } = counterSlice.actions;export default counterSlice.reducer;
3.通过 Redux Toolkit 的 configureStore 来创建和配置 store
// store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './slices/counterSlice';export const store = configureStore({reducer: {counter: counterReducer,},
});
4.组件中使用
a. 首先,在应用的最顶层组件(App.js)中使用<Provider>组件包裹你的应用,将store传递给它
// index.js 或 App.js,根据你的项目结构来决定
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App'; // 这是你的应用组件
import { store } from './store'; // 确保从 store.js 正确导入 storeReactDOM.render(<Provider store={store}><App /></Provider>,document.getElementById('root')
);
b. 然后,在需要访问Redux store的组件中使用useSelector来读取状态,使用useDispatch来分发action
// Counter.jsx
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, add } from '../store/reducer';const Counter = () => {const count = useSelector((state: any) => state.counter.value);const dispatch = useDispatch();return (<div><h2>Counter: {count}</h2><button onClick={() => dispatch(increment())}>Increment</button><button onClick={() => dispatch(decrement())}>Decrement</button><button onClick={() => dispatch(add(9))}>Decrement</button></div>);
};export default Counter;