当我试图将父数据传递给子组件时,我总是碰壁。
我的看法:
<%= react_component 'Items', { data: @items } %>
我的 Items
组件进行 ajax 调用、设置状态并呈现 Item
。将 key={this.props.id}
保留在传递到映射函数的 Item
实例之外,以便组件 html 呈现到页面。但是添加 key 后,我收到控制台错误:Uncaught TypeError: Cannot read property 'id' of undefined
这是“项目”:
var Items = React.createClass({
loadItemsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function() {
this.loadItemsFromServer();
},
render: function() {
var itemNodes = this.props.data.map(function() {
return (
<Item key={this.props.id} />
);
});
return (
<div className="ui four column doubling stackable grid">
{itemNodes}
</div>
);
}
});
我的 item.js.jsx 组件只是格式化每个 Item
:
var Item = React.createClass({
render: function() {
return (
<div className="item-card">
<div className="image">
</div>
<div className="description">
<div className="artist">{this.props.artist}</div>
</div>
</div>
);
}
});
React 开发工具扩展显示了 Items 内的 props 和状态数据。然而, children 却是空的。
我知道this ,但我正在使用 this.props.id
设置 key 。我不确定我错过了什么?
最佳答案
我发现您在 Items
组件中发布的代码存在一些问题
- 您正在渲染
this.props.data
,而实际上this.state.data
是通过 ajax 请求更新的数据。您需要渲染this.state.data
但从props
获取初始值 - map 迭代器函数接受一个表示当前数组元素的参数,使用它来访问属性,而不是使用未定义的 this
更新后的代码应如下所示
var Item = React.createClass({
render: function() {
return (
<div className="item-card">
<div className="image">
</div>
<div className="description">
<div className="artist">{this.props.artist}</div>
</div>
</div>
);
}
});
var Items = React.createClass({
getInitialState: function() {
return {
// for initial state use the array passed as props,
// or empty array if not passed
data: this.props.data || []
};
},
loadItemsFromServer: function() {
var data = [{
id: 1,
artist: 'abc'
}, {
id: 2,
artist: 'def'
}]
this.setState({
data: data
});
},
componentDidMount: function() {
this.loadItemsFromServer();
},
render: function() {
// use this.state.data not this.props.data,
// since you are updating the state with the result of the ajax request,
// you're not updating the props
var itemNodes = this.state.data.map(function(item) {
// the map iterator function takes an item as a parameter,
// which is the current element of the array (this.state.data),
// use (item) to access properties, not (this)
return (
// use key as item id, and pass all the item properties
// to the Item component with ES6 object spread syntax
<Item key={item.id} {...item} />
);
});
return (
<div className="ui four column doubling stackable grid">
{itemNodes}
</div>
);
}
});
关于ruby-on-rails - 如何避免reactjs中的key/id问题并使 Prop 从父级传递到子级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37624649/