react js中如何知道组件渲染情况
how to know the component rendering condition in react js
我有一个组件也呈现为子组件,或者用户可以直接从 UI 的菜单导航到该组件。我现在面临的一个问题是,如果该组件作为子组件那么它工作正常但是当我单击菜单直接导航时我的 getDerivedStateFromProps() 函数抛出错误
TypeError: Cannot read property 'length' of undefined
下面是我的代码。如果我将数据从父组件发送到该组件并从父组件呈现它,它将正常工作。
static getDerivedStateFromProps(props, state) {
if (props.data.length)// this line is throwing an error when I directly come to this component from menu {
const data = props.data;
return { custData : data };
}
return null;
}
如果我直接来到这个组件,如何检查不执行上述逻辑的条件。
您可以这样仔细检查:
if (props.data && props.data.length)
查看数据是否存在
if (props?.data)
我有一个组件也呈现为子组件,或者用户可以直接从 UI 的菜单导航到该组件。我现在面临的一个问题是,如果该组件作为子组件那么它工作正常但是当我单击菜单直接导航时我的 getDerivedStateFromProps() 函数抛出错误
TypeError: Cannot read property 'length' of undefined
下面是我的代码。如果我将数据从父组件发送到该组件并从父组件呈现它,它将正常工作。
static getDerivedStateFromProps(props, state) {
if (props.data.length)// this line is throwing an error when I directly come to this component from menu {
const data = props.data;
return { custData : data };
}
return null;
}
如果我直接来到这个组件,如何检查不执行上述逻辑的条件。
您可以这样仔细检查:
if (props.data && props.data.length)
查看数据是否存在
if (props?.data)