随记react

  1. 使用对象管理多个状态
    可以使用一个 useState 钩子管理一个对象,所有相关的变量都放在该对象中。
import React, { useState, useEffect } from 'react';

const Home  =  ()  => {

	  const [state, setState] = useState({
		    getCode: '',
		    version: '高级版',
		    validity: '2025-03-04',
		    balance: 2333,
		    status: { ongoing: 0, success: 0, failed: 0 },
	  });
	  
	  useEffect(() => {
		    setState((prevState) => ({ ...prevState, getCode: 1111})); 
	  }, []);

	  return (
	    <div>
	      <div>{state.getCode}</div>
	      <div>{state.version}</div>
	      <div>{state.validity}</div>
	      <div>{state.balance}</div>
	    </div>
	  );};export default Home;

优点
使用一个状态对象将多个变量组织在一起。
更新状态时,使用展开运算符 … 保留未修改的字段。

  1. 使用 useReducer
    当状态较为复杂且需要更新逻辑时,使用 useReducer 是一种更优雅的选择
import React, { useReducer, useEffect } from 'react';

// 定义初始状态
const initialState = {
		  getCode: '',
		  version: '高级版',
		  validity: '2025-03-04',
		  balance: 2333,
		  status: { ongoing: 0, success: 0, failed: 0 },
	};
	
	// 定义 reducer 函数
	function reducer(state, action) {
	  switch (action.type) {
	    case 'SET_CODE':
	      return { ...state, getCode: action.payload };
	    case 'SET_BALANCE':
	      return { ...state, balance: action.payload };
	    case 'SET_STATUS':
	      return { ...state, status: { ...state.status, ...action.payload } };
	    default:
	      return state;
	  }
	}
	
	const Home = () => {
	  const [state, dispatch] = useReducer(reducer, initialState);
	  useEffect(() => {
	    dispatch({ type: 'SET_CODE', payload: 111}); // 更新状态
	  }, []);
	  
  return (
   <div>
	      <div>{state.getCode}</div>
	      <div>{state.version}</div>
	      <div>{state.validity}</div>
	      <div>{state.balance}</div>
    </div>
  );
};

export default Home;

优点
适合复杂的状态管理。
状态更新逻辑集中在 reducer 中,便于维护和扩展。

  1. 使用自定义 Hook
    如果某些状态逻辑是重复的,可以封装成自定义 Hook。

import React, { useEffect, useState } from ‘react’;

// 自定义 Hook

function useQueryParameter(key) {
  const [value, setValue] = useState('');

  useEffect(() => {
    const queryParams = new URLSearchParams(window.location.search);
    setValue(queryParams.get(key) || '');
  }, [key]);

  return value;
}

const Home = () => {
  const getCode = useQueryParameter('code'); // 自动解析 URL 参数

  return (
    <div>
      <div>{getCode}</div>
    </div>
  );
};

export default Home;

优点
可复用的状态逻辑,避免重复代码。
自定义 Hook 简化了某些常用场景的实现。

总结
少量状态:可以直接用多个 useState。
多状态、相关状态:用单个状态对象或 useReducer。
重复逻辑:封装自定义 Hook。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值