如何引用react redux
安装依赖
确保项目已安装react-redux和redux库。通过npm或yarn安装:
npm install react-redux redux
# 或
yarn add react-redux redux
创建Redux Store
在根目录下创建store,通常放在src/store/index.js中:
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
export default store;
定义Reducer
创建reducer文件(如src/store/reducers.js)处理状态逻辑:

const initialState = {
count: 0
};
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
default:
return state;
}
};
export default rootReducer;
提供Store到React
在应用入口文件(如src/index.js)中使用Provider包裹根组件:
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')
);
连接组件
在组件中使用connect或Hooks(如useSelector和useDispatch)访问状态和操作:

使用connect(类组件)
import React from 'react';
import { connect } from 'react-redux';
const Counter = ({ count, increment }) => (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
const mapStateToProps = (state) => ({
count: state.count
});
const mapDispatchToProps = (dispatch) => ({
increment: () => dispatch({ type: 'INCREMENT' })
});
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
使用Hooks(函数组件)
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
const Counter = () => {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
</div>
);
};
export default Counter;
异步操作(可选)
使用redux-thunk或redux-saga处理异步逻辑。以redux-thunk为例:
- 安装中间件:
npm install redux-thunk - 修改store配置:
import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
3. 定义异步action:
```javascript
const fetchData = () => (dispatch) => {
fetch('api/data').then(res =>
dispatch({ type: 'SET_DATA', payload: res.data })
);
};






