react 笔记

react 中将一个个元素视为组件,通过组合拼接形成一个页面。
每一个函数视为一个组件。
jsx语法:js中嵌套xml,return出组件的dom元素

组件

hook函数

1.useState 添加状态变量,控制组件渲染效果
const [count,setCount] = useState(0);

2.useContext 添加上下文变量,用与跨组件通讯

	1.创建上下文对象 
		const msgContext = useContext();

	2.顶层组件通过<msgContext.Provider msg={msg}>传递信息 

	3.底层通过hook函数接收
		const msg = useContext(msgContext)

3.useEffect
用于非事件而由渲染引起的操作
=>页面的重新渲染会调用这个函数
useEffect(()=>{ },[]);

	1. 第一个函数是要执行的操作,被称为【副作用函数】=> 用于处理组件的副作用,即不直接产生组件UI而是与组件生命周期相关的逻辑。

	2. 第二个参数是依赖参数,不同的参数会改变useEffect执行的条件
		无参数时:仅在初始化时调用一次
		空数组时:初始化和页面重新渲染都会调用
		特定依赖:特定依赖变化时执行=======>例如参数为状态变量count,每次仅count(其他操作不会)更新时都会调用

	3. 清除副作用函数
		在副作用函数中可以添加一个return,其中的代码会在组件被销毁时执行
		
		例:
			useEffect(()=>	{ 	
						//副作用函数;
						return ()=>{ //清除副作用逻辑} 
					},[]);

4.自定义hook实现

	一般定义成use开头的函数,实现逻辑的封装和复用

	1. 声明函数
		function useToggle(){}
	2.可复用的代码逻辑
		function useToggle(){
			const [value,setValue] = useState(true);
			const toggle = ()=>setValue(!value);
		}
	3.return出需要使用的变量
		function useToggle(){
			const [value,setValue] = useState(true);
			const toggle = ()=>setValue(!value);
			return {value,toggle}
		}
	4.在想要使用的地方接收这些参数
		const {value,toggle} = useToggle();	//return出的是一个对象,接收也需要写成对象

5.Redux
redux是一种可以批量管理组件状态的工具
当项目复杂起来时,组件间的通讯变得极为难以维护,这时使用redux让项目变得有序

1.创建一个reducer(state,action)纯函数
	接收当前状态state,和更新操作action

2.createStore(reducer)使用创建的reducer函数创建store对象

3.store.subscribe()方法可以监听数据变化,数据更新时调用
	返回一个可以取消监听的函数,调用停止监听。

4.store.dispatch(action)方法可以action通知store更新状态

5.store.getState()方法获取当前状态

例子:
//定义reducer
    function reducer(state={count:0},action){
        if(action.type === "INCREASE"){
            return {count : state.count + 1};
        }
        if(action.type === "DECREASE"){
            return {count : state.count - 1};
        }
        return state;
    }

    //创建store
    const store = Redux.createStore(recuder);

    //监听数据变化
    store.subscribe(()=>{
        console.log("数据变化",store.getState());
        document.getElementById("content").textContent = store.getState().count;
    });

    //发送状态的更新
    const incrBtn = document.getElementById("increase");
    const decrBtn = document.getElementById("decrease");

    incrBtn.addEventListener("click",()=>{
        store.dispatch({type:"INCREASE"});
    });
    decrBtn.addEventListener("click",()=>{
        store.dispatch({type:"DECREASE"});
    });

6.redux与react搭配使用
由于redux可以独立于框架运行,在搭配使用时我们需要连接react
需要下载两个工具库

  • Redux Toolkit
  • react-redux
    前者是一套工具合集,简化书写redux的逻辑
    后者是连接redux和react的工具
    在控制台中输入 npm i @reduxjs/toolkit react-react 下载
    npm : 为包管理工具
    i : install下载
    @reduxjs/toolkit : Redux Toolkit别名
    react-react : react-react

*需要创建一个store.js
```
import { configureStore } from '@reduxjs/toolkit'
配置一个store
export default configureStore({
reducer: {},
})


  *在index.js中引用
    ```
import store from './app/store'

    const root = ReactDOM.createRoot(document.getElementById('root'))
    root.render(
      <Provider store={store}>
        <App />
      </Provider>,
    )

*创建一个counter切片

import { createSlice } from '@reduxjs/toolkit'

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
  },
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
  },
})
//此处调用的actions返回的是生产action的函数
//调用increment()返回一个action对象,通过这个对象调用dispatch方法来更新当前状态
export const { increment, decrement} = counterSlice.actions
export default counterSlice.reducer

createSlice()方法根据你传入的对象返回一个对象,其中包括:
reducer:这是一个已经创建好的 reducer 函数,它接收当前状态和 action 对象作为参数,并返回一个新的状态。这个 reducer 函数是根据你在 createSlice 中定义的 initialState 和 reducers 自动生成的。
actions:这是一个对象,包含了与这个 slice 相关联的所有 action 创建函数。这些函数在被调用时会返回包含正确 type 和 payload(如果有的话)的 action 对象。这些 action 对象随后会被 Redux store 接收,并传递给相应的 reducer 函数以更新状态。
name:这是 slice 的名称,它用于生成 action 类型的字符串。这个名称通常是在 createSlice 的配置对象中指定的。
注:并且这个方法会自动为您生成了相关的action创建函数(action creators)和action类型(action types)。我们只需要通过导出的reducer

*在store.js中引用定义的切片

import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./modules/counterSlice";  


const store =  configureStore({
    reducer:{
        counter:counterReducer
    },
})

export default store;

*在组件中使用定义的状态
import { useDispatch, useSelector } from "react-redux";
import { increment, decrement } from "./store/modules/counterSlice";

function App() {
  const {value} = useSelector(state =>state.counter);
  const dispatch = useDispatch();
  return (
    <div className="App">
      <button onClick={()=>{dispatch(decrement())}}>-</button>
      {value}
      <button onClick={()=>{dispatch(increment())}}>+</button>
    </div>
  );
}

export default App;

状态管理的流程图

7.redux-react 异步状态操作
7.1 创建store
configureStore和createStore
一、基本功能
createStore:
是Redux的核心API,用于创建一个Redux store来存放应用中所有的state。
需要传递一个reducer函数作为参数,reducer函数根据action来更新state。
可以选择性地传递一个初始状态(initState)和一个增强器(enhancer)作为参数。
configureStore:
是Redux Toolkit提供的一个高级API,用于配置和创建Redux store。
它简化了store的创建过程,并提供了更好的默认配置,如中间件和reducer的自动组合。
允许开发者通过传递一个包含reducer和其他配置选项的对象来创建store。
二、配置和灵活性
createStore:
需要手动组合多个reducer(如果使用combineReducers的话)。
需要手动添加中间件(如使用applyMiddleware)。
需要手动处理Redux DevTools的集成(如果使用的话)。
configureStore:
自动处理reducer的组合,只需要传递一个包含多个reducer的对象。
提供了默认的中间件配置(如Redux Thunk),但也可以自定义中间件。
自动集成Redux DevTools,方便开发者进行调试。

7.2创建一个thunk函数

为了与 dispatch 普通 action 对象保持一致,我们通常将它们写为 thunk action creators,它返回 thunk 函数。这些 action creator 可以接受可以在 thunk 中使用的参数。
const logAndAdd = (amount) => {
  return (dispatch, getState) => {
    const stateBefore = getState();
    console.log(`Counter before: ${stateBefore.counter}`);
    dispatch(incrementByAmount(amount));
    const stateAfter = getState();
    console.log(`Counter after: ${stateAfter.counter}`);
  };
};
可以通过dispatch(logAndAdd(5) )来dispatch一个thunk函数,这个函数会被中间件捕捉,这个函数中可以执行dispatch一般的action creators,也可以执行其余操作
posted @   衔蝉奴2001  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示