简体   繁体   English

反应原生,object state 上的 useEffect 不起作用

[英]React native, the useEffect on a object state not working

Here is the code before the render这是渲染前的代码

const HappyComponent = (props) => {
    console.log(JSON.stringify(props));    // the props are ok

    const [HHDays, setHHDays] = useState(null);
    useEffect(() => {
        const hours = props.infos.happy ?
            {
                allWeek: { from: props.infos.ending, to: props.infos.strating, showPickerFrom: false, showPickerTo: false },
            }
            :
            {
                allWeek: { from: "", to: "", showPickerFrom: false, showPickerTo: false },
            }
        setHHDays(hours);
        console.log(JSON.stringify(HHDays));
    }, []);

    return (

So the state of HHDays stays null and the render shows an error on the frist {HHDays.allWeek.from}所以stateHHDays保持null并且渲染在第一个{HHDays.allWeek.from}上显示错误

TypeError: null is not an object (evaluating 'HHDays.allWeek')类型错误:null 不是 object(评估“HHDays.allWeek”)

useEffect is called after the component was rendered. useEffect在组件渲染后调用。 So when the code reaches that line the first time around, it tries to read null.from .因此,当代码第一次到达该行时,它会尝试读取null.from

Maybe you'd want to move all that which is inside the useEffect inside useState , as the default value.也许您想将useEffect中的所有内容移到useState中,作为默认值。 You don't actually need a useEffect here.您实际上并不需要useEffect在这里。

const [HHDays, setHHDays] = useState(props.infos.happy ?
            {
                allWeek: { from: props.infos.ending, to: props.infos.strating, showPickerFrom: false, showPickerTo: false },
            }
            :
            {
                allWeek: { from: "", to: "", showPickerFrom: false, showPickerTo: false },
            });

Try passing an empty object to useState instead of null尝试将一个空的 object 传递给 useState 而不是 null

const [HHDays, setHHDays] = useState({});

SetState is an asynchronous call, meaning, its unclear if the state is changed when the code reaches the log. SetState 是一个异步调用,也就是说,当代码到达日志时,不清楚 state 是否发生了变化。 If you need to make sure the state is set, you can use a timeout or a useeffect based on state changes.如果您需要确保设置了 state,您可以根据 state 的更改使用超时或使用效果。

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

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