我的数据如下所示
team1 : {
author92 : "John" ,
author43 : "Smith"
},
team2 : {
author33 : "Dolly",
author23 : "Mark"
},
并且我希望像下面这样按组显示作者,但是添加author计数器而不管哪个团队。
集团1
1,John
2,Smith
集团2
3,多莉
4,马克
我现在的显示器是这样的
集团1
1,John
2,Smith
集团2
1,多莉
2,马克
我无法控制数据的结构,但我首先要遍历团队,并将数据传递给React应用程序中的组件。
{Object.values(data).map((key) => {
return (
<p>Group <span>{key + 1}</span></p>
<Team authorCounter={} />
)
}
我的团队组件在文章中循环并显示作者
const author = Object.keys(data.team1).map((key) => {
return {
<b>{key + 1}.</b> }
我想知道如何传递添加到另一个上面的作者的数量,这样我就可以开始在子组件中给作者编号。
发布于 2017-11-01 21:32:24
由于数据对于组件来说不是可用状态,我建议您首先将数据映射到可用状态,并预先计算索引。
这可能会给排序和反转带来问题,但这意味着您需要将映射移动到GroupContainer
组件,而不是移出它之外。
const data = {
team1 : {
author92 : "John" ,
author43 : "Smith"
},
team2 : {
author33 : "Dolly",
author23 : "Mark"
}
};
const Member = ({ member }) => {
return <p>{ member.index}, { member.name }</p>;
};
const Group = ({ index, teams }) => {
return <div><p>Group { index }</p>{ teams.map( team => <Member member={team} /> ) }</div>;
};
class GroupContainer extends React.Component {
render() {
let counter = 0, childCounter = 0;
let { data } = this.props;
return <div>{ data.map( group => <Group {...group} /> ) }</div>;
}
}
function mapData( data, childCount = 0 ) {
return Object.keys( data ).map( (group, index) => {
let obj = data[group];
return {
index: index + 1,
name: group,
teams: Object.keys( obj ).map( author => ({
index: ++childCount,
name: obj[author]
}) )
};
});
}
ReactDOM.render( <GroupContainer data={ mapData( data ) } />, document.querySelector('#app') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app">
</div>
发布于 2017-11-01 21:51:39
这是你的工作密码。如果不需要状态,则可以使用功能组件。
https://jsfiddle.net/sfr7hmf3/
const obj = {
team1 : {
author92 : "John" ,
author43 : "Smith"
},
team2 : {
author33 : "Dolly",
author23 : "Mark"
},
};
class App extends React.Component {
render() {
const teams = [];
let teamNum = 1;
let authorsStartWith = 1;
Object.keys(obj).forEach(key => {
teams.push({
team: obj[key],
teamNum,
authorsStartWith,
});
teamNum += 1;
authorsStartWith += Object.keys(obj[key]).length;
});
return (
<div>
{
teams.map(team =>
<Team
team={team.team}
teamNum={team.teamNum}
authorsStartWith={team.authorsStartWith}
key={team.teamNum}
/>
)
}
</div>
)
}
}
class Team extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<p>Group {this.props.teamNum}</p>
<ol start={this.props.authorsStartWith}>
{
Object.values(this.props.team)
.map(authorName =>
<li
key={`${this.props.groupName}_${authorName}`}
>
{authorName}
</li>)
}
</ol>
</div>
);
}
}
发布于 2017-11-01 21:08:40
在使用++
时,可以对计数和增量使用闭包。
https://stackoverflow.com/questions/47063501
复制相似问题