vite4加react18加ts-状态管理篇

vite4加react18加ts-安装篇; 最近从vue3转型学习了,react相关技术架构,去有意识的去学习了相关东西,内容比较实用,没有引入太多原理和概念,就是最直接最实用的记录下来;

安装
npm install @reduxjs/toolkit
npm install react-redux
概念
redux: 是的官方 React UI 绑定层,允许您的 React 组件从 Redux 存储中读取数据,
并将操作分派到存储以更新状态。
@reduxjs/toolkit:是对 Redux 的二次封装,开箱即用可的一个高效的 Redux
开发工具集,使得创建store、更新store。
项目中版本
"@reduxjs/toolkit": "^1.9.1",
"react-redux": "^8.0.5",  
创建store目录
src▽
  store▽
     slices▽
        user.tsx
   index.tsx
编写src/store/slices/user.tsx
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
interface UserState {
    name: string;
    age: number;
}
const initialState: UserState = {
    name: '器灵',
    age: 20
}
export const userSlice = createSlice({
    name: 'user',
    // state数据的初始值
    initialState: initialState,
    reducers: {
      setName(state, action: PayloadAction<string>) {
        // 第一个参数 state 为当前state中的数据
        // 第二个参数action为{payload,type:'user/setName'}
        state.name = action.payload
      },
      setAge(state, action: PayloadAction<number>) {
        state.age = action.payload
      }
    }
  });
  // 导出外部给组件调用, 也可以不导出
  export const { setName, setAge } = userSlice.actions;
编写src/store/index.txs
import { configureStore } from '@reduxjs/toolkit'
import { userSlice } from './slices/user';
const store = configureStore({
    reducer: {
      user: userSlice.reducer //user module
    },
    devTools: true
});
// 定义 ts types
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export default store;
使用store
import ReactDOM from 'react-dom/client'
import App from './App'
import { Provider } from 'react-redux';
import store from './store/index';
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <Provider store={store}>
    <App />
  </Provider>
);
组件中使用
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from '@/store/index';
import { setName } from '@/store/slices/user';
function Login() {
		const { user } = useSelector((state: RootState) => state);
    const dispatch = useDispatch();
    return(
    	<div>
      	<div>{user.name}</div>
        // 第一种方法调用user暴露方法
        <button onClick="() => {
        	dispatch(setName('掘金'));
        }">修改userName</button>
        /* 第二种直接修改 type: 'user/xxx';
          	 user: 对应slices/user中对应name; 
            '/xxx'; xxx: 对应slices/user中reducers定义方法名
        */
        <button onClick="() => {
        	dispatch({type: 'user/setName', payload: '绝金-稀土'});
        }">修改userName</button>
      </div>
    )
}
export default Login;

你可能感兴趣的:(javascript,前端,react)