我正在尝试在创建React组件时实现Presentational和Container Components模式。所以我创建了一个只包含UI元素和容器组件的表示组件,并具有处理数据功能。
import React from "react";
const MyComponent = ({props}) => (
<div>
{props.games.map((game, index) => (
<div key={index}>
{game.index + 1} - {game.contestName}
</div>
))};
</div>
);
export default MyComponent;
import React, { Component } from "react";
import MyComponent from "./component";
class MyContainer extends Component {
constructor(props) {
super(props);
this.state = {
games: [
{
id: 1,
categoryName: "Business/Company",
contestName: "Name1"
},
{
id: 2,
categoryName: "Magazine/Newsletter",
contestName: "Name2"
},
{
id: 3,
categoryName: "Software Component",
contestName: "Name3"
},
{
id: 4,
categoryName: "Website",
contestName: "Name4"
}
]
};
}
render() {
return (
<div>
<MyComponent games={this.state.games} />
</div>
);
}
}
export default MyContainer;
但是,我无法呈现数据而且
无法读取未定义的属性“游戏”。
非常感谢您的帮助,因为两天的互联网挖掘并没有产生积极的结果。
答案 0 :(得分:2)
const MyComponent = ({props}) => (
执行此操作时,实际上是
{ props: props-received-from-parent }
您将道具封闭在另一个对象中,删除那些大括号并将该行更改为
const MyComponent = (props) => (
你很高兴。
答案 1 :(得分:1)
您应该构建games
而不是props
:
import React from "react";
const MyComponent = ({games}) => (
<div>
{games.map((game, index) => (
<div key={index}>
{game.index + 1} - {game.contestName}
</div>
))};
</div>
);
export default MyComponent;
答案 2 :(得分:0)
您可以像这样定义MyComponent类
class MyComponent extends Component{
render(){
this.xyz = this.props.games.map((item,index) => {
return(<div key={index}>{item.id}</div>)
})
return(
<div>
{this.xyz}
</div>
)
}
}
export default MyComponent;
这也有效!