Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React项目使用key属性优化非列表 #41

Open
jiangshanmeta opened this issue Aug 13, 2021 · 0 comments
Open

React项目使用key属性优化非列表 #41

jiangshanmeta opened this issue Aug 13, 2021 · 0 comments
Labels

Comments

@jiangshanmeta
Copy link
Owner

背景:

const FormDrawer = ()=>{
    const {
        loading,
        forceRenderContent,
        children
    } = props;

    if(loading){
        if(forceRenderContent){
            return (
                <>
                    <Skeleton />
                    <div >
                        {children}
                    </div>
                </>
            )
        }
        return <Skeleton />
    }
    return (
        <>
            <div >
                {children}
            </div>
            <div>
                btn
            </div>
        </>
    )
}

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

    const setLoaded = ()=>{
        setLoading(false);
    }
    
    return (
        <FormDrawer
            forceRenderContent
            loading={loading}
        >
            <MyForm setLoaded={setLoaded} />
        <FormDrawer/>
    )
}

MyForm 初始化的时候会发一堆请求,请求都响应了再调用setLoaded通知父组件加载完成。一个偶然的机会我发现所有请求都会被发送两次,进而发现 在MyForm调用 setLoaded之后 会被卸载 ,然后重新挂载一个新的。

const FormDrawer = ()=>{
    const {
        loading,
        forceRenderContent,
        children
    } = props;

    if(loading){
        if(forceRenderContent){
            return (
                <>
                    <Skeleton />
                    <div key="children">
                        {children}
                    </div>
                </>
            )
        }
        return <Skeleton />
    }
    return (
        <>
            <div key="children">
                {children}
            </div>
            <div>
                btn
            </div>
        </>
    )
}

还是虚拟DOM做diff的时候 由于匹配不上就粗暴把旧的节点卸载了,key属性帮助react匹配节点

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant