react如何获取redux数据
获取 Redux 数据的常用方法
使用 useSelector Hook(函数组件推荐)useSelector 是 React-Redux 提供的 Hook,可直接从 Redux store 中提取数据。

import { useSelector } from 'react-redux';
function MyComponent() {
const data = useSelector((state) => state.yourReducerKey);
return <div>{data}</div>;
}
使用 connect 高阶组件(类组件适用)
通过 mapStateToProps 将 Redux 状态映射到组件的 props。
import { connect } from 'react-redux';
class MyComponent extends React.Component {
render() {
return <div>{this.props.data}</div>;
}
}
const mapStateToProps = (state) => ({
data: state.yourReducerKey,
});
export default connect(mapStateToProps)(MyComponent);
直接访问 Store(不推荐)
在极少数情况下,可以直接通过 store.getState() 获取数据,但通常应优先使用上述方法。
import store from './your-store';
const data = store.getState().yourReducerKey;
注意事项
- 性能优化:
useSelector默认使用严格相等(===)比较,若返回新对象可能导致不必要的渲染。可使用浅比较或记忆化选择器。 - 多层级数据:在
useSelector或mapStateToProps中按需选择最小数据,避免全局状态依赖。







