react redux如何使用
安装依赖
在项目中安装 Redux 和 React-Redux 库:
npm install redux react-redux
创建 Redux Store
定义一个 reducer 函数,并使用 createStore 创建 store:
import { createStore } from 'redux';
// 初始状态
const initialState = { count: 0 };
// Reducer 函数
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
};
// 创建 store
const store = createStore(reducer);
使用 Provider 包裹应用
在根组件中使用 Provider 将 store 传递给整个应用:
import { Provider } from 'react-redux';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
在组件中访问状态
使用 useSelector 获取状态,useDispatch 派发 action:
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
<span>{count}</span>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
</div>
);
}
异步操作(使用 Redux Thunk)
安装中间件并配置 store 以支持异步 action:
npm install redux-thunk
修改 store 配置:
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(reducer, applyMiddleware(thunk));
定义异步 action:
const fetchData = () => {
return async (dispatch) => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
dispatch({ type: 'SET_DATA', payload: data });
};
};
组织代码(模块化)
将 reducer、action 和 store 拆分为单独文件:
actions.js定义 action 创建函数。reducers.js组合多个 reducer(使用combineReducers)。store.js集中配置 store。
示例:
// reducers.js
import { combineReducers } from 'redux';
import counterReducer from './counterReducer';
export default combineReducers({
counter: counterReducer,
});
// store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
export default createStore(rootReducer, applyMiddleware(thunk));
使用 Redux DevTools
安装浏览器扩展,并在 store 中启用:
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);






