react如何传递redux
传递 Redux 到 React 组件
在 React 中使用 Redux 需要结合 react-redux 库,通过 Provider 和 connect 或 Hooks 实现状态管理。
使用 Provider 包裹根组件
在应用的入口文件(如 index.js)中,用 Provider 包裹根组件,并将 Redux store 作为 prop 传递。这样所有子组件均可访问 store。

import { Provider } from 'react-redux';
import store from './store'; // 假设 store 已配置
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
类组件中使用 connect
通过 connect 高阶组件将 Redux 的 state 和 dispatch 映射到组件的 props。定义 mapStateToProps 和 mapDispatchToProps 后,包裹目标组件。

import { connect } from 'react-redux';
import { someAction } from './actions';
class MyComponent extends React.Component {
render() {
return <div>{this.props.someData}</div>;
}
}
const mapStateToProps = (state) => ({
someData: state.someReducer.data,
});
const mapDispatchToProps = { someAction };
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
函数组件中使用 Hooks
在函数组件中,使用 useSelector 获取 state,用 useDispatch 触发 action。
import { useSelector, useDispatch } from 'react-redux';
import { someAction } from './actions';
function MyComponent() {
const someData = useSelector((state) => state.someReducer.data);
const dispatch = useDispatch();
return (
<button onClick={() => dispatch(someAction())}>
{someData}
</button>
);
}
直接访问 Store(不推荐)
在极少数情况下,可直接通过 store 实例调用 getState() 或 dispatch(),但通常优先使用上述方法。
import store from './store';
const currentState = store.getState();
store.dispatch({ type: 'SOME_ACTION' });
关键注意事项
- 避免直接修改 state:Redux 要求纯函数更新 state,需通过 reducer 返回新对象。
- 性能优化:
connect和useSelector会浅比较 props,避免不必要的渲染。 - 中间件:如需异步逻辑,可集成
redux-thunk或redux-saga等中间件。






