最初的回答:我有一个场景,在这个场景中我正在将数据从一个reducer传递到我的React状态中。
数据:
使用componentWillReceiveProps,这对于检索标题的操作非常完美。最初的回答。
然而,我在获取嵌套字段时遇到了困难。当我执行以下操作时:
但这也行不通,我认为是因为博客未定义。最初的回答。
数据:
{
"id": 1,
"title": "Test",
"content": {
"body": "sdfsdf"
"image": "http://example.com"
}
}
使用componentWillReceiveProps,这对于检索标题的操作非常完美。最初的回答。
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps.blog.title,
})
}
然而,我在获取嵌套字段时遇到了困难。当我执行以下操作时:
但是:
componentWillReceiveProps(nextProps) {
console.log("new title is", nextProps.blog.title);
console.log("new body content is", nextProps.blog.content["body"]);
this.setState({
title: nextProps.blog.title,
body: nextProps.blog.content["body"]
})
}
我遇到了这个错误:
在我点击调试器并加载内容后,未定义的正文错误消失了。有没有办法解决这个问题?
我尝试像这样检查未定义:
Original Answer:
if (typeof nextProps.blog.content["body"] != 'undefined'){
但这也行不通,我认为是因为博客未定义。最初的回答。