首页 > 解决方案 > React props 函数变得未定义

问题描述

我在父组件中定义了一个函数。我将函数传递给子组件。当我在子组件中调用函数时,出现错误: TypeError: updateModifiers is not a function

记录typeof显示该函数在第一次渲染时定义,然后在接下来的两次渲染中变为未定义:

function
undefined
undefined

为什么会是updateModifiers被覆盖的原因?我不知道发生了什么..

const Product = ({
    ...
}) => {
    ...

    const updateModifiers = (modifierId, options) => {
        ...
    }

    return (
        <Drawer anchor="bottom" open={open} onClose={closeDrawer}>
            ...
            <ProductModifiers current={selection} updateModifiers={updateModifiers} />
            ...
        </Drawer>
    )
}

export default Product

const ProductModifiers = ({ current, updateModifiers }) => {
    console.log("parent", typeof updateModifiers)

    if (Object.keys(current.modifiers).length === 0)
        return null

    return (
        <Fragment>
            {Object.values(current.modifiers).sort((a, b) => a.order - b.order).map((modifier, i) =>
                <ProductModifier key={i} modifier={modifier} updateModifiers={updateModifiers} />
            )}
        </Fragment>
    )
}

const ProductModifier = ({ modifier, updateModifiers }) => {
    console.log("child", modifier.name, typeof updateModifiers)
    ...

    useEffect(() => {
        console.log(typeof updateModifiers) // <-- returns function -> undefined -> undefined
        // updateModifiers(modifier.name, options)
    }, [options])

    return (
        ...
    )
}

更新:(如果有帮助)

Object.values(current.modifiers)inProductModifiers有两个元素。对于第一个元素,函数定义明确。对于第二个,不是。

parent function
child Toppings function
child Toppings function
child Sides undefined
child Sides undefined
parent function
child Toppings function
child Toppings function
child Sides undefined
child Sides undefined

为什么updateModifiers在第二个渲染组件中未定义?

更新2

发现问题。与我在其他地方的代码有关。不过,问这个问题帮助我调试!;-)

标签: reactjs

解决方案


您是否尝试删除抽屉组件以检查它是否不会在 ProductModifiers 上引入一些副作用?


推荐阅读