我正在尝试渲染通过道具来的数据(对象)。但是,出现以下错误:
Uncaught TypeError: Cannot convert undefined or null to object
尽管在data
期间更新了componentDidMount()
的状态,但我不知道为什么数据或对象为null。您能帮我为什么数据为空吗?
请查看class A
,以了解如何使用数据
class A extends React.Component {
state = {
data: null
};
componentDidMount() {
this.data = this.props.location.state.data;
this.setState({ data: this.props.location.state.data });
}
render() {
return (
<div>
{Object.keys(this.data).map((key, index) => (
<p key={index}> value is {this.data[key]}</p>
))}
hello
</div>
);
}
}
A.propTypes = {
data: PropTypes.object,
location: PropTypes.object
};
export default A;
假设this.data
包含以下格式的数据
{
id: 1,
userName: "ABDXY",
date: "01/12/2020",
time: "21:00"
}
答案 0 :(得分:1)
this.data
未定义。您可以使用this.state.data
请确保this.props.location.state.data
不为空
class A extends React.Component {
state = {
data: {}
};
componentDidMount() {
// this.data = this.props.location.state.data; => not required.
this.setState({
data: this.props.location.state.data
});
}
render() {
return ( <
div > {
Object.keys(this.state.data).map((key, index) => ( <
p key = {
index
} > value is {
this.state.data[key]
} < /p>
))
}
hello <
/div>
);
}
}
答案 1 :(得分:0)
从状态而不是this.data
获取数据,因为它不会在this.data
更新时触发渲染。还要使用{}
作为默认值
class A extends React.Component {
state = {
data: {}
};
componentDidMount() {
const data = {
id: 1,
userName: "ABDXY",
date: "01/12/2020",
time: "21:00"
};
this.setState({ data });
}
render() {
const { data } = this.state;
return (
<div>
{Object.keys(data).map((key, index) => (
<p key={index}> value is {data[key]}</p>
))}
hello
</div>
);
}
}
export default A;