繁体   English   中英

如何访问未初始化的 state 挂钩的属性?

[英]how to access a property of a state hook that´s not initialized?

如果 state 尚未设置,如何在组件中安全地使用 object? 我将它初始化为 null (我可以使用 {} 但这会导致其他影响)。 我得到:

无法读取未定义的属性“名称”

const [user, setUser] = useState(null);
someService(user => setUser(user))
const someRef = useRef(null);

if (!user) {
    // to avoid the undefined user.name I tried this but it causes an issue with useRef (because the actual someRef is not rendered when !user
    return <p>loading user</p>
}

return (
    <div>
        <p>{user.name}</p>
        <div ref={someRef}>hello</div>
    </div>
)

工作示例: https://codesandbox.io/s/young-dust-y2z5k?fontsize=14&hidenavigation=1&theme=dark

此时尚未创建用户,我们应该渲染“加载用户”,这很好,但 someRef 导致问题,因为有消息但未渲染组件。 取消注释第 5 行和注释第 6 行以查看它是否正常工作

尝试:

const [user, setUser] = useState(null);
someService(user => setUser(user))

render(){
    return({user? <p>{user.name}</p> :<p>loading user</p>});
}

您可以在 ref 和用户更改上使用useEffect来设置另一个变量,以便:

import React, { useState, useEffect } from 'react'

export default function Test() {
    const [user, setUser] = useState(null);
    const someRef = useRef(null);
    const [loaded, setLoaded] = useState(false);

    useEffect(() => {
        if (user && someRef) {
            setLoaded(true)
        }
    }, [user, someRef])

    return (
        loaded ?
            <div>
                <p>{user.name}</p>
                <div ref={someRef}>hello</div>
            </div> : <div>not loaded yet</div>
    )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM