Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

怎么处理 react hook 依赖问题?

不懂就问,假如有以下 hooks:

import React from 'react';

const Demo = () => {
    const { userId } = useUser();
    const { address } = useUserAddress(userId);
    const { favious } = useUserFavious(userId);
    
    return (
        <div>Hello World</div>
    );
};

其中,useUserAddressuseUserFavious依赖userId的值,我如何确保userId获取成功后才运行下面的 hooks。目前想到的方案:

  • 方案一:在 useUserAddressuseUserFavious 里判断userId 是否存在值。但是这样如果 hooks 多,每个都得加这个判断很繁琐
  • 方案二:把后面的hooks提取到子组件或者 HOC:
import React from 'react';

const ChildrenDemo = ({ userId }) => {
    const { address } = useUserAddress(userId);
    const { favious } = useUserFavious(userId);
    
    return (
        <div>Hello World</div>
    );
};

const Demo = () => {
    const { userId } = useUser();
    
    if(!userId) return null;
    
    return <ChildrenDemo userId={userId} />
};

请问有没有更好的处理方式吗?感觉都挺麻烦的


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

试试?

useEffect(() => {
    new Promise(res => {
        const { userId } = useUser();
        res(userId);
    }).then(data => {
        const { address } = useUserAddress(userId);
        const { favious } = useUserFavious(userId);
    })
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...