簡體   English   中英

如何使用 react 自定義鈎子使代碼可重用

[英]How do I use react custom hooks to make code reusable

我有兩個類似的組件,如下所示:

const Login = props => {
    let loading;
    const dispatch = useDispatch();
    const [notification, setNotification] = React.useState('');
    const [hasNotification, setHasNotification] = React.useState('');
    const [isLoading, setIsLoading] = React.useState(false);
    const {status, message} = useSelector(state => state.LoginReducer);
    const { register, handleSubmit, formState, errors } = useForm({
        mode: "onChange"
    });
    const onSubmit = data => {
        setIsLoading(true);
        dispatch(loginStart(data));
    };
    React.useEffect(() => {
        setIsLoading(false);
        if (status === 422) {
            setNotification(message);
            setHasNotification('ERROR');
            return;
        }
        if (status === 200) {
            setNotification(message);
            setHasNotification('SUCCESS');
        }
    }, [status, message]);
    React.useEffect(() => {
        console.log('componentDidMount');
        return () => {
            setNotification('');
            setHasNotification('');
        };
    }, []);
    return (
        <AuthLayout title={'Login'} header={'Welcome back, Sign in'} hasNotification={hasNotification} notification={notification}>
        </AuthLayout>
    )
}
export default Login;

我還有另一個與上述功能相似的組件

const Signup = props => {
    let loading;
    const dispatch = useDispatch();
    const [notification, setNotification] = React.useState('');
    const [hasNotification, setHasNotification] = React.useState('');
    const [isLoading, setIsLoading] = React.useState(false);
    const {status, message} = useSelector(state => state.SignupReducer);
    const { register, handleSubmit, formState, errors } = useForm({
        mode: "onChange"
    });
    const onSubmit = data => {
        setIsLoading(true);
        dispatch(signupStart(data));
    };
    React.useEffect(() => {
        setIsLoading(false);
        if (status === 422) {
            setNotification(message);
            setHasNotification('ERROR');
            return;
        }
        if (status === 200) {
            setNotification(message);
            setHasNotification('SUCCESS');
        }
    }, [status, message]);
    React.useEffect(() => {
        console.log('componentDidMount');
        return () => {
            setNotification('');
            setHasNotification('');
        };
    }, []);
    return (
        <AuthLayout title={'Signup'} header={'Discover a new way to do amazing work'} hasNotification={hasNotification} notification={notification}>
        </AuthLayout>
    )
}
export default Signup;

我閱讀了自定義掛鈎,但只是好奇如何將 state 和邏輯移動到單獨的自定義掛鈎 function,因為它們具有相似的結構和功能。

自定義鈎子會是什么樣子?

您可以在 function 中聲明所有狀態/掛鈎邏輯並將其導出到您的組件:

示例:對於您的登錄組件,您可以將您的邏輯提取到一個文件中,我們稱之為useLogin.js

useLogin.js

export default () => {
    const [notification, setNotification] = React.useState('');
    const [hasNotification, setHasNotification] = React.useState('');
    const [isLoading, setIsLoading] = React.useState(false);
    const { register, handleSubmit, formState, errors } = useForm({
        mode: "onChange"
    });
    React.useEffect(() => {
        setIsLoading(false);
        if (status === 422) {
            setNotification(message);
            setHasNotification('ERROR');
            return;
        }
        if (status === 200) {
            setNotification(message);
            setHasNotification('SUCCESS');
        }
    }, [status, message]);
    React.useEffect(() => {
        console.log('componentDidMount');
        return () => {
            setNotification('');
            setHasNotification('');
        };
    }, []);
   return [notification, hasNotification, setIsLoading]; //return all variable and functions that you need in your component
}

在登錄中,您應該導入您的 function 並使用它

import useLogin from './useLogin'; // first import useLogin function
const Login = props => {
    let loading;
    const dispatch = useDispatch();
    const {status, message} = useSelector(state => state.LoginReducer);
    const [notification, hasNotification, setIsLoading] = useLogin(); // call useLogin and get notification and hasNotification objects
    const onSubmit = data => {
        setIsLoading(true);
        dispatch(loginStart(data));
    };
    return (
        <AuthLayout title={'Login'} header={'Welcome back, Sign in'} hasNotification={hasNotification} notification={notification}>
        </AuthLayout>
    )
}
export default Login;

與注冊組件相同

import useLogin from './useLogin';
const Signup = props => {
    let loading;
    const dispatch = useDispatch();
    const {status, message} = useSelector(state => state.SignupReducer);
    const [notification, hasNotification, setIsLoading] = useLogin();
    const onSubmit = data => {
        setIsLoading(true);
        dispatch(signupStart(data));
    };
    return (
        <AuthLayout title={'Signup'} header={'Discover a new way to do amazing work'} hasNotification={hasNotification} notification={notification}>
        </AuthLayout>
    )
}
export default Signup;

希望這個想法很清楚;

您可以使用相同的代碼創建一個新組件,不同之處在於標題和來自 AuthLayout 的 header

<AuthLayout title={props.title} header={props.header} hasNotification={hasNotification} notification={notification}></AuthLayout>

登錄

const Login = props => {
    return (
        <newComponent title={'Login'} header={'Welcome back, Sign in'} />
    )
}
export default Login;

報名

const SignUp = props => {
    return (
        <newComponent title={'SignUp'} header={'Discover a new way to do amazing work'} />
    )
}
export default SignUp;

我調用了 newComponent,您將創建的組件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM