【发布时间】:2015-04-21 21:11:19
【问题描述】:
我有一个 React 类,它想渲染一个如下所示的对象:
data: {
title: "haha",
description: {
country: "US",
year: "1996"
}
}
但是,当 React 想要渲染它时,它给出了一个错误。
未捕获的错误:不变违规:receiveComponent(...):只能更新已安装的组件
我认为问题出在 getInitialState 中,我将我的数据声明为一个空对象,所以当我在超时后获得完整的数据对象时,React 会尝试将我的数据对象映射到组件,但它给出了错误。
但有趣的是,我访问 this.props.title.title 没有问题,但访问 this.props.title.description.country 没有问题,它会给未定义
但是,当我 console.log 时,我可以看到我的对象。但是 React 无法访问它!
我的猜测是当 React 从空对象初始化时,它只会用数据对象的第一和第二级初始化虚拟 DOM。
那是因为,当我尝试访问 this.props.data.data.title 是可以的,但不是 this.props.data.data.description.country
下面是我的代码
var BookBox = React.createClass({
getInitialState: function() {
return { data: {} };
},
componentWillMount: function() {
var that = this;
setTimeout(function() {
console.log('timeout');
that.setState({
data: {
title: "haha",
description: {
country: "US",
year: "1996"
}
}
});
}, 2000);
},
render: function() {
return (
<div>
<h1>{this.state.data.title}</h1>
<TestBox title={this.state.data} />
</div>
);
}
});
var TestBox = React.createClass({
render: function() {
console.log(this.props.title);
return (
<div>
<p>{ this.props.title.description.country }</p>
<p>{ this.props.title.title }</p>
</div>
);
}
})
我可以知道处理这个问题的最佳方法是什么吗?我应该在 getInitialState 中初始化我的数据对象结构还是有更好的方法?
【问题讨论】:
标签: javascript reactjs