关于减少 React useState hooks 数量的建议。

3
我正在尝试构建自己的第一个相对较大的项目,至少对于我的经验水平来说是如此。 我在很大程度上依赖于useContext与useStates hooks的组合来处理不同组件之间的逻辑。随着时间的推移,跟踪所有这些不同状态的变化和简单的onClick事件开始变得困难,我必须更改许多状态的逻辑。
希望能得到一点个人建议,指引我正确的方向。 因为我做的事情似乎并不正常,或者这就是React的现实吗? 肯定有更聪明的方法来减少状态逻辑管理的数量。
以下是我正在使用的一些代码片段。
  const onClick = (note: INote) => {
    SetAddNote(false);
    SetNote(note);
    onSelected(note)
    SetReadOnly(true);
    SetEditor(note.data.value);
    SetInputValue(note.data.name);
    SetCategory(note.data.category);
  };

  const { note, noteDispatch, SetNoteDispatch } = useContext(NoteContext);
  const { categories } = useContext(CategoriesContext);
  const [ editMode, setEditMode ] = useState(false);
  const [ module, setModule ] = useState<{}>(modulesReadOnly)
  const [inputValue, setInputValue] = useState<string>('');
  const [category, setCategory] = useState('');
  const [color, setColor] = useState('');

import React, { createContext, useState } from 'react';


type EditorContextType = {
  editor: string;
  SetEditor: React.Dispatch<React.SetStateAction<string>>;
  readOnly: boolean;
  SetReadOnly: React.Dispatch<React.SetStateAction<boolean>>;
  inputValue: string;
  SetInputValue: React.Dispatch<React.SetStateAction<string>>;
  category: string;
  SetCategory: React.Dispatch<React.SetStateAction<string>>;
};

type EditorContextProviderProps = {
  children: React.ReactNode;
};

export const EditorContext = createContext({} as EditorContextType);

export const EditorContextProvider = ({
  children,
}: EditorContextProviderProps) => {
  const [editor, SetEditor] = useState('');
  const [readOnly, SetReadOnly] = useState(false)
  const [inputValue, SetInputValue] = useState('');
  const [category, SetCategory] = useState('');
  return (
    <EditorContext.Provider value={{ editor, SetEditor, readOnly, SetReadOnly, inputValue, SetInputValue, category, SetCategory  }}>
      {children}
    </EditorContext.Provider>
  );
};

我可以将几个州合并成一个,但似乎这样会比现在更加复杂。

我正在阅读有关useReducer钩子的文章,然而很难完全理解其背后的整个思想,也不确定它是否真的能帮助我解决这个问题。 如果我继续以这种方式工作,我感觉自己注定要失败,但我没有看到任何更好的实现选项。


笔记,编辑器,输入值和类别均源自 onClick 中的 note 参数。你能否只设置一个值来代替这 5 个单独状态呢?然后在需要时稍后检索嵌套属性(例如 note.data.category)。 - CertainPerformance
如果没有足够的重叠使这些状态可以结合起来,那么在没有更多信息的情况下,我认为你所做的事情是没有问题的。这需要大量的样板代码,这是不幸的(使用许多状态和TS会带来这种情况),但它不是糟糕的代码。也许,现在不用担心它。 - CertainPerformance
这绝对不是世界末日,但我刚刚开始编写代码,就已经有这么多状态了,情况会变得更糟,太多事件导致状态改变,我几乎无法再跟踪它们了。 - Georgi
1个回答

2
我也在从事大型项目,正如您在问题中所说,Reducer将帮助您解决问题,但是您必须小心地构建和管理状态。因此,管理状态的想法非常重要。在我回答之前,我将写一些重要的注意事项:
  1. 尽可能减少嵌套上下文,只有在需要时才构建上下文和使用上下文,这将优化您的工作。
  2. 对于处理或合并状态,可以使用对象、数组和普通变量,但请记住,尽量避免嵌套级别过多的对象,以便在状态更改时保持状态更新。
  3. 使用reducer来处理状态更新将给您带来很好的能力。
  4. 我们可以通过在reducer中设置条件来进行一些技巧以提高性能,其中它检查旧状态和新状态。
请记住,真的很容易使用,但是第一次学习可能很难...
现在让我们从一个真实的项目示例开始:
// create VirtualClass context
export const JitsiContext = React.createContext();

// General Action
const SET_IS_SHARED_SCREEN = 'SET_IS_SHARED_SCREEN';
const SET_ERROR_TRACK_FOR_DEVICE = 'SET_ERROR_TRACK_FOR_DEVICE';
const UPDATE_PARTICIPANTS_INFO = 'UPDATE_PARTICIPANTS_INFO';
const UPDATE_LOCAL_PARTICIPANTS_INFO = 'UPDATE_LOCAL_PARTICIPANTS_INFO';

// Initial VirtualClass Data
const initialState = {
  errorTrackForDevice: 0,
  participantsInfo: [],
  remoteParticipantsInfo: [],
  localParticipantInfo: {}
};

// Global Reducer for handling state
const Reducer = (jitsiState = initialState, action) => {
  switch (action.type) {
    case UPDATE_PARTICIPANTS_INFO:// Update particpants info and remote list
      if (arraysAreEqual(action.payload, jitsiState.remoteParticipantsInfo)) {
        return jitsiState;
      }

      return {
        ...jitsiState,
        participantsInfo: [jitsiState.localParticipantInfo, ...action.payload],
        remoteParticipantsInfo: action.payload,
      };
    case UPDATE_LOCAL_PARTICIPANTS_INFO:// Update particpants info and local one
      if (JSON.stringify(action.payload) === JSON.stringify(jitsiState.localParticipantInfo)) {
        return jitsiState;
      }

      return {
        ...jitsiState,
        localParticipantInfo: action.payload,
        participantsInfo: [action.payload, ...jitsiState.remoteParticipantsInfo],
      };
    case SET_IS_SHARED_SCREEN:
      if (action.payload === jitsiState.isSharedScreen) {
        return jitsiState;
      }

      return {
        ...jitsiState,
        isSharedScreen: action.payload,
      };
    default:
      throw new Error(`action: ${action.type} not supported in VirtualClass Context`);
  }
};


const JitsiProvider = ({children}) => {
  const [jitsiState, dispatch] = useReducer(Reducer, initialState);
  
  // Update shared screen flag
  const setIsSharedScreen = useCallback((flag) => {
    dispatch({type: SET_IS_SHARED_SCREEN, payload: flag})
  }, []);

  // Update list of erros
  const setErrorTrackForDevice = useCallback((value) => {
    dispatch({type: SET_ERROR_TRACK_FOR_DEVICE, payload: value})
  }, []);
  
  // Local Participant info
  const updateLocalParticipantsInfo = useCallback((value) => {
    dispatch({type: UPDATE_LOCAL_PARTICIPANTS_INFO, payload: value})
  }, []);
  
  const updateParticipantsInfo = useCallback(async (room, currentUserId = null) => {
    if (!room.current) {
      return;
    }

    // get current paricipants in room
    let payloads = await room.current.getParticipants();
    // ... some logic
    let finalResult = payloads.filter(n => n).sort((a, b) => (b.startedAt - a.startedAt));
    dispatch({type: UPDATE_PARTICIPANTS_INFO, payload: finalResult})
  }, []);

  const contextValue = useMemo(() => {
    return {
      jitsiState,
      setIsSharedScreen,
      setErrorTrackForDevice,
      updateParticipantsInfo,
      updateLocalParticipantsInfo,
    };
  }, [jitsiState]);

  return (
    <JitsiContext.Provider
      value={contextValue}
    >
      {children}
    </JitsiContext.Provider>
  );
};

export default JitsiProvider;

这个例子允许您更新状态并且有多种情况,所有状态值都通过jitsiState共享,因此您可以获取任何所需的数据,至于功能方面,您可以直接使用dispatch!但是根据我们的经验,我们建立了一个回调方法并通过提供程序发送它,这样可以使代码和逻辑集中在一处,并使过程变得非常容易,因此当单击任何地方时只需要调用所需的方法...

您还将看到条件和useMemo...这些是为了防止不必要的触发器渲染,例如更改内存中的键而不是实际值等...

最终,我们现在可以轻松控制所有组件之间的状态,并且除了包装器上下文之外,我们没有嵌套的上下文。

注意:您肯定可以根据自己的逻辑或需要的概念跳过或更改此代码。

注意2:此代码进行了修改以便更容易阅读或理解...

注意3:您可以忽略传递给提供程序的所有函数并直接使用dispatch,但是在我的项目中,我会像此示例一样发送一个函数。


这看起来非常有前途,我还需要消化一下,但我应该能够使用那个示例代码并构建类似的东西,谢谢。 - Georgi
不客气!我希望它能对你有所帮助,在我的项目中,它让我的生活变得更加轻松... - Anees Hikmat Abu Hmiad
@Georgi 在我看来,使用 reducer 方法会导致更多的样板代码而收益不大...但这取决于你。 - CertainPerformance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接