reactjs - 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:
发现问题。与我在其他地方的代码有关。不过,问这个问题帮助我调试!;-)
解决方案
您是否尝试删除抽屉组件以检查它是否不会在 ProductModifiers 上引入一些副作用?
推荐阅读
- python-3.x - Python - 实现 numpy.corrcoef
- sql-server - SQL Server 加密函数是否具有确定性?
- google-api - google-calendar-api 的方法 service.events().list 返回超出时间范围的数据
- javascript - 即使在被分配了一个值之后,键也是空的
- r - 使用应用功能时如何添加要排除的条件
- javascript - 无法使用 .exit() .remove() api 删除选定的 D3 SVG 元素
- uwp - UWP 应用程序失败 WACK 并出现多个错误
- php - 提取距离较近的 SPACE 和某个字符之间的子字符串
- react-native - 创建一个可重用的 React Native 模态组件
- azure-data-lake - U-SQL 输出器的提示并行化