如何react和redux
React 基础使用
React 是一个用于构建用户界面的 JavaScript 库。它采用组件化的方式构建应用,每个组件管理自己的状态和 UI。
安装 React:
npx create-react-app my-app
cd my-app
npm start
基本组件示例:
import React from 'react';
function App() {
return <h1>Hello World</h1>;
}
export default App;
Redux 核心概念
Redux 是一个可预测的状态容器,帮助管理应用状态。主要包含三个部分:
- Store:保存应用状态
- Action:描述状态变化
- Reducer:根据action更新状态
安装Redux:
npm install redux react-redux
React与Redux集成
创建Redux store:
import { createStore } from 'redux';
import { Provider } from 'react-redux';
const initialState = { count: 0 };
function reducer(state = initialState, action) {
switch(action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
}
const store = createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
连接组件到Redux
使用connect函数将React组件连接到Redux store:
import { connect } from 'react-redux';
function Counter({ count, increment }) {
return (
<div>
<p>{count}</p>
<button onClick={increment}>+</button>
</div>
);
}
const mapStateToProps = state => ({
count: state.count
});
const mapDispatchToProps = dispatch => ({
increment: () => dispatch({ type: 'INCREMENT' })
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter);
Redux中间件
Redux中间件可以处理异步操作,常用redux-thunk:
npm install redux-thunk
配置中间件:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
reducer,
applyMiddleware(thunk)
);
异步action示例:
function fetchData() {
return dispatch => {
fetch('/api/data')
.then(res => res.json())
.then(data => dispatch({ type: 'SET_DATA', payload: data }));
};
}
Redux Toolkit简化开发
Redux Toolkit是官方推荐简化Redux代码的工具:
npm install @reduxjs/toolkit
使用示例:
import { configureStore, createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => {
state.value += 1;
},
},
});
const store = configureStore({
reducer: {
counter: counterSlice.reducer,
},
});
现代React与Redux实践
使用React Hooks与Redux交互:

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>
);
}






