react如何结合redux
React 结合 Redux 的步骤
安装必要的依赖包,确保项目中有 react-redux 和 redux。通过以下命令安装:
npm install react-redux redux
创建 Redux Store
在 src 目录下创建 store.js 文件,用于初始化 Redux store:
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
export default store;
定义 Reducer
创建 reducers 文件夹,定义根 reducer。例如 index.js:
import { combineReducers } from 'redux';
import counterReducer from './counterReducer';
const rootReducer = combineReducers({
counter: counterReducer,
});
export default rootReducer;
示例子 reducer(counterReducer.js):
const initialState = {
count: 0,
};
const counterReducer = (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;
}
};
export default counterReducer;
连接 React 组件
使用 Provider 包裹根组件,将 store 传递给整个应用。修改 src/index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
在组件中使用 Redux
通过 useSelector 和 useDispatch Hook 访问状态和触发 action。例如 Counter.js:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
const Counter = () => {
const count = useSelector((state) => state.counter.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
};
export default Counter;
异步 Action 处理(可选)
如需处理异步逻辑(如 API 调用),可使用 redux-thunk 中间件。安装后配置 store:
npm install redux-thunk
修改 store.js:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
定义异步 action:
const fetchData = () => {
return async (dispatch) => {
dispatch({ type: 'FETCH_START' });
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
dispatch({ type: 'FETCH_SUCCESS', payload: data });
} catch (error) {
dispatch({ type: 'FETCH_ERROR', error });
}
};
};






