开发者问题收集

React native,对象状态上的 useEffect 不起作用

2022-08-04
553

这是渲染之前的代码

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 (

因此 HHDaysstate 保持 null 并且渲染在第一个 {HHDays.allWeek.from 上显示错误

TypeError: null is not an object (evaluating 'HHDays.allWeek')

3个回答

useEffect 在组件渲染后调用。因此,当代码第一次到达该行时,它会尝试读取 null.from

也许您想将 useEffect 中的所有内容移到 useState 中,作为默认值。您实际上不需要这里 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 },
            });
jperl
2022-08-04

尝试将空对象传递给 useState,而不是 null

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

Jorge Gomez
2022-08-04

SetState 是一个异步调用,也就是说,当代码到达日志时,尚不清楚状态是否已更改。如果您需要确保状态已设置,则可以使用超时或基于状态更改的 useeffect。

Darren Landig
2022-08-04