在 reactjs 中清理具有多个切换状态的代码

Clean up code with multiple toggle states in reactjs

我有几个带有 antd 库的按钮,我想为每个按钮添加加载状态。我创建多个状态来控制这些加载

const [loading, setLoading] = useState(true);

const [loadingSave, setLoadingSave] = useState(false); //for save button

const [loadingDelete, setLoadingDelete] = useState(false); //for delete button

const [loadingDownload, setLoadingDownload] = useState(false); //for download button

这行得通,但我的代码似乎很乱。如果有更多的按钮需要加载动画,那就更糟了。无论如何重构这个? 提前致谢!

您可以对包含这些值的对象使用单一状态。

例如:

const [loadingStates, setLoadingStates] = useState({
    loading: true,
    loadingSave: false,
    loadingDelete: false,
    loadingDownload: false,
});

要更改值,您可以使用:

setLoadingStates(prevObject => {
    return {
        ...prevObject,
        loading: false,
    }
});

希望对您有所帮助

一种干净的方法是使用 React hook useReducer 添加更多状态会更容易和更干净。 要掌握 useReducer,请查看此博客 https://blog.logrocket.com/react-usereducer-hook-ultimate-guide/

在 React 文档中,React 不建议对数据对象使用一个 useState

建议使用多个useState。

    
    
    const initialState = {
        loading: true,
        loadingSave: false,
        loadingDelete: false,
        loadingDownload: false,
    };
   
   
   function handlingStatesReducer(state, action) {
        switch (action.type) {
            case 'setState': {
                return {
                    ...state,
                    [action.fieldName!]: action.payload,
                };
            }
            default:
                return state;
        }
    }
    
    
    
    const [state, dispatch] = useReducer(handlingStatesReducer, initialState);
    const { loadingDownload, loadingDelete, loadingSave, loading } = state;
    
    
    /// To setState 
    
      dispatch({
                    type: "setState",
                    fieldName: "loading",
                    payload: false
                })