新的 React Hook useState 返回未定义

Rhi*_*omb 16 javascript undefined reactjs redux react-hooks

useState() 给我未定义的新状态变量(通知):

const Notifications = (props) => {
    const [notifications, setNotifications] = useState(props.notifications);//notifications = undefined, props = {notifications: Array(0)}
    useEffect(() => {
        if (props.notifications) {
        setNotifications(props.notifications);
        }
    }, [props.notifications]);
    // do stuff....
Run Code Online (Sandbox Code Playgroud)

我期待通知[],然后随后setNotifications()props.notifications更改时更新它。props.notification来自 redux 商店。我不知道这是否会改变任何东西,但我确实设置了一个初始状态。

const initialState = Immutable.fromJS({
  notifications: [],
});
Run Code Online (Sandbox Code Playgroud)

不知道为什么我变得未定义...

编辑:摆脱了错字和测试代码

jay*_*rjo 9

要正确设置初始状态,您应该将其useState作为参数传递给,因此:

const [notifications, setNotifications] = useState([]);
Run Code Online (Sandbox Code Playgroud)

此外,无论您是否props.notifications在某处设置外部,但如果您依赖它在组件中具有某种默认值,那么您应该将其设置在那里,例如:

const Notifications = ({ notifications = [] }) => {
Run Code Online (Sandbox Code Playgroud)

最后但并非最不重要的是,在依赖项列表中使用数组useEffect有一些不需要的副作用,例如,如果notifications结构将保持不变(相同的项目,相同的长度),但将是一个新数组,useEffect将错过缓存,因为它只做一个肤浅的比较。考虑使用某种散列函数而不是数组本身(例如JSON.stringify

  • 我建议创建新数组,而不是使用哈希函数。新状态?更改值的全新对象。 (2认同)