Reducer数据结构
{
items: [
{
images: 'http://xxxx.jpg',
buttons: [
{
text: '购买',
bgColor: '#fff',
},
{
text: '查看详情',
bgColor: '#fff',
}
]
},
{ // 篇幅有限结构同上 },
{ // 篇幅有限结构同上 },
]
}
这是一个轮播图的数据结构,一个item
一张图,图上也许会有button
。
基础component
组件三个: Button
,SingleImage
,Carousel
最终成型代码如下
class Demo extends React.Component {
componentDidMount() {
// dispatch(action)获取ajax数据等一系列操作,最终this.props.data为上述结构的数据
}
render() {
<Carousel>
{
this.props.data.items.map((item, index) => (
<SingleImage
key={ index }
data={ item }
dispatch={ this.props.dispatch }
/>
))
}
}
</Carousel>
}
}
在组件SingleImage
中渲染Button
也是大致类似数据驱动:
// jsx
<div>
this.props.buttons.map(button => (
<Button data={ button } />
))
</div>
需求是用户可以编辑按钮上的文字,即在Button
组件中改变Reducer
中的item[x]buttons[y].text
。我不解的地方是如何确定这里的x
和y
,即哪个图下的哪个按钮。我有想法是把SingleImage
和Button
的key
传入该Button
组件中,作为Action
的参数但是总感觉不合适,组件就不能完全解耦了。还请各位前辈赐教。
你的思路是对的,而且个人感觉是唯一办法,因为对于每个SingleImage和Button而言,只有map的时候可以确定索引值。
至于耦合的问题,可以考虑把Button做成无状态组件,点击逻辑在SingleImage中完成,这样可以做到Button解耦。
SingleImage很难做到松耦合,除非点击逻辑外置,这样需要多层传递,代价比较大。
或者更极端一点,SingleImage和Button做成一个无状态组件,点击逻辑放到Demo中