1、安装
npm install react-redux
2、创建store.js
import { createStore } from 'redux';// 定义初始状态
const initialState = {counter: 888
};// 定义 reducer 函数,根据 action 类型更新状态
function reducer(state = initialState, action) {switch (action.type) {case 'INCREMENT':return {...state, counter: state.counter + 1 };case 'DECREMENT':return {...state, counter: state.counter - 1 };default:return state;}
}// 创建 store
const store = createStore(reducer);export default store;
3、在主文件index.tsx全局引入
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
// redux全局参数
import { Provider } from 'react-redux';
import store from './store/store.js';const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement
);
root.render(<Provider store={store}><React.StrictMode><App /></React.StrictMode></Provider>
);
reportWebVitals();
4、使用
1、在两个tex文件引入使用查看效果
第一个tex文件
//引入
import store from '../store/store';console.log("大得333")
//获得打印
console.log(store.getState().counter)
//修改
store.getState().counter = 6666
第二个文件
import store from './store/store';
function dade(){// 获取状态console.log("大得")console.log(store.getState().counter)store.getState().counter = 999console.log(store.getState().counter)
}
dade()
效果