我在使用.map()
方法迭代父組件的狀態對象(ChildOne)以創建另一個子組件的多個實例時遇到困難(ChildTwo )。this.props.parentprop.map不是函數(TypeError)
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
listItems: [] // this list
}
render() {
return (
<div>
<ChildTwo listItems={this.state.listItems} />
</div>
}
爲ChildOne,在那裏可以找到錯誤:
class TrackList extends React.Component {
render() {
console.log(this.props.items); // returns the array in parent state with no problem
return (
<div>
{this.props.items.map(item => { // this.props.items.map is not a function
return (
<ChildTwo item={item} key={item.id} />
)})
}
</div>
最後,對於ChildTwo:
class ChildTwo extends Component {
render() (
return (
<div>
<ChildOne items={this.props.listItems} />
</div>
由於沒有在tracklist組件中給出適當的道具,因此沒有listItem變量在ChildTwo組件中進行了展示,您還有另一個已由@Austin Greco解釋的錯誤 –