【发布时间】:2021-12-19 01:46:00
【问题描述】:
我正在尝试构建我自己的第一个相对较大的项目,至少就我的经验水平而言。 我严重依赖 useContext 和 useStates 挂钩来处理我的不同组件之间的逻辑,随着时间的推移,跟踪所有这些不同的状态变化和简单的 onClick 事件真的开始变得困难,我必须改变逻辑大量的州。
希望能得到一些个人建议,引导我朝着正确的方向前进。 不知何故,我的所作所为感觉不正常,或者这就是 React 的现实? 肯定有更聪明的方法来减少状态逻辑管理的数量吗?
这是我正在使用的一些 sn-ps 代码
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参数。你有没有机会简单地为笔记设置 one 值,而不是 5 个单独的状态?然后在需要时检索嵌套属性(例如note.data.category)。 -
如果没有 - 如果实际上没有足够的重叠来实际组合这些状态 - 那么,如果没有更多信息,我认为你正在做的事情没有任何问题。它需要大量的样板,这是不幸的(使用大量状态和 TS),但它不是 bad 代码。也许,别担心。
-
当然还不是世界末日,但我刚开始写代码,已经有这么多状态,它会变得更糟,太多事件的太多状态变化,我几乎没有可以再跟踪它了。
标签: reactjs use-state state-management use-context use-reducer