Redux 通常用于管理 React 应用程序的状态,特别是在大型和复杂的应用程序中。
 在 React 应用程序中,组件的状态通常由组件自身管理。然而,当应用程序变得复杂时,状态管理可能会变得困难,因为需要在多个组件之间共享和同步状态。这就是 Redux 发挥作用的地方。
使用 Redux,你可以将应用程序的状态存储在一个全局的 Redux store 中。然后,你可以使用 Redux 的 connect 函数将 React 组件连接到 Redux store,使它们能够访问和更新状态。在项目中使用redux
- 
安装react-redux npm install react-redux 
- 
创建 Redux store 
 在项目根目录下创建一个名为 store.js 的文件,用于存放 Redux store 和 reducer。
  // store.js 
 import { createStore } from 'redux';
 // 一个名为 counterReducer 的函数,
 // 它接收两个参数:state 和 action。
 // state 是当前的计数器值,默认为 0。
 // action 是一个包含 type 属性的对象,表示要执行的操作。
 function counterReducer(state = 0, action) {
 switch (action.type) {
 case 'INCREMENT':
 return state + 1;
 case 'DECREMENT':
 return state - 1;
 default:
 return state;
 }
 }
 // 创建一个 Redux store,并将 reducer 传递给它:
 export const store = createStore(counterReducer);
- 
在 React 组件中使用 Redux store 
 修改 src/App.js 文件,导入 Provider 组件并将 Redux store 传递给它。然后,创建一个 Counter 组件,如之前的例子所示,并将其导 出
  // src/App.js 
 import React from 'react';
 //它允许在一个父组件中存储数据,并且使任何子组件都能够访问到这些数据,
 //而不管它们在组件树中的深度如何。
 import { Provider } from 'react-redux';
 import { store } from './store';
 import Counter from './Counter';function App() { 
 return (
 <Provider store={store}>
 <Counter />
 </Provider>
 );
 }export default App; 
- 
创建 Counter 组件 
 在 src 目录下创建一个名为 Counter.js 的文件,编写一个连接到 Redux store 的 Counter 组件
  
            
            
              javascript
              
              
            
          
          // src/Counter.js
import React from 'react';
import { connect } from 'react-redux';
function Counter({ value, onIncrement, onDecrement }) {
    return (
        <div>
            <h1>{value}</h1>
            <button onClick={onIncrement}>+</button>
            <button onClick={onDecrement}>-</button>
        </div>
    );
}
// mapStateToProps 用于将 Redux store 的状态映射到组件的 props
function mapStateToProps(state) {
    return { value: state };
}
// mapDispatchToProps 用于将 Redux store 的 dispatch 方法映射到组件的 props
function mapDispatchToProps(dispatch) {
    return {
        onIncrement: () => dispatch({ type: 'INCREMENT' }),
        onDecrement: () => dispatch({ type: 'DECREMENT' }),
    };
}
export default connect(mapStateToProps, mapDispatchToProps)(Counter);