redux如何关联react
关联 Redux 与 React 的核心步骤
安装依赖
确保项目中已安装 redux 和 react-redux 包。通过以下命令安装:
npm install redux react-redux
创建 Redux Store
在 store.js 中定义 reducer 并初始化 store:

import { createStore } from 'redux';
const initialState = { count: 0 };
function rootReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
default:
return state;
}
}
const store = createStore(rootReducer);
export default store;
使用 Provider 包裹根组件
在应用入口文件(如 index.js)中,用 Provider 传递 store:
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
通过 connect 或 Hooks(如 useSelector 和 useDispatch)访问 store:

类组件写法(connect)
import React from 'react';
import { connect } from 'react-redux';
function Counter({ count, increment }) {
return (
<div>
<p>{count}</p>
<button onClick={increment}>+</button>
</div>
);
}
const mapState = (state) => ({ count: state.count });
const mapDispatch = (dispatch) => ({
increment: () => dispatch({ type: 'INCREMENT' })
});
export default connect(mapState, mapDispatch)(Counter);
函数组件写法(Hooks)
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<p>{count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
</div>
);
}
export default Counter;
关键概念说明
- Provider:使 store 对组件树全局可用。
- connect:高阶组件,将 state 和 dispatch 映射到组件 props。
- Hooks:简化函数组件与 Redux 的交互,避免嵌套高阶组件。
通过以上步骤,Redux 的状态管理即可与 React 组件无缝集成。






