redux如何关联react
redux与react的关联方法
redux通过react-redux库与react进行关联,该库提供Provider和connect(或hooks)两种核心方式实现状态管理与组件的绑定。
使用Provider注入store
在react应用的根组件外层包裹Provider组件,并将redux的store作为props传递。这样所有子组件均可访问store:

import { Provider } from 'react-redux';
import store from './redux/store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
类组件中使用connect
通过connect高阶函数将redux的state和dispatch映射到组件的props:
import { connect } from 'react-redux';
class MyComponent extends React.Component {
render() {
return <div>{this.props.someState}</div>;
}
}
const mapStateToProps = (state) => ({
someState: state.someReducer
});
const mapDispatchToProps = { fetchData }; // action creators
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
函数组件中使用hooks
react-redux提供useSelector和useDispatch替代connect:

import { useSelector, useDispatch } from 'react-redux';
function MyComponent() {
const someState = useSelector(state => state.someReducer);
const dispatch = useDispatch();
return (
<button onClick={() => dispatch(fetchData())}>
{someState}
</button>
);
}
中间件集成
在创建store时可通过中间件(如redux-thunk)增强dispatch能力:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
类型安全(TypeScript)
使用TypedUseSelectorHook定义类型化的hooks:
import { TypedUseSelectorHook, useSelector } from 'react-redux';
import { RootState } from '../store';
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;






