我正在创建一排10张牌。每张卡都需要自己调用API来获取一个移动网址。如何使用React / Redux实现这一目标?
以下是我的React Card组件。我循环遍历此组件10次,每次使用不同的cardId
,卡用来调用API来获取图片网址。
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {fetchRendition} from '../../../actions/RenditionAction';
class Card extends Component {
componentDidMount() {
// action call to fetch rendition for card
this.props.fetchRendition(this.props.cardId);
}
render() {
return (
<div className='card'>
<div className='card-image-container'>
<div className='card-image' style = {{backgroundImage: `url(${this.props.rendition.url})`}}/>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {rendition: state.card}
}
export default connect(mapStateToProps, {fetchRendition})(Card);
循环显示此卡组件如下所示:
import React, {Component} from 'react';
class RowOfCards extends Component {
render() {
const ArrayOfIds = ['id1', 'id2', 'id3', 'id4','id5', 'id6', 'id7', 'id8'. 'id9', 'id10']
return ArrayOfIds.map((id) => <Card cardId = {id}/>))
}
}
export default RowOfCards;
目前,通过此实施,所有10张卡片都以相同的图像结束。预期的行为是每张卡应该有不同的图像。在每张卡调用API后,如何使用自己的图像更新卡片?
答案 0 :(得分:1)
您似乎正在使用更新的图像替换reducer中的图像,因为您的reducer中只有一个rendition
图像,所有卡都使用相同的图像。
对于你的用例,似乎不需要redux,你需要的是将图像存储在Card组件状态,除了Card组件之外没有人知道它自己的图像。
export default class Card extends Component {
state = {
rendition: {}
}
componentDidMount() {
// action call to fetch rendition for card
fetchRendition(this.props.cardId).then((res) => { // make an api call and store the response in state and not in redux store
this.setState({rendition: res})
});
}
render() {
return (
<div className='card'>
<div className='card-image-container'>
<div className='card-image' style = {{backgroundImage: `url(${this.state.rendition.url})`}}/>
</div>
</div>
);
}
}
Redux @dan_abramov的作者写了一篇关于You might not need redux
的文章。请看看它
答案 1 :(得分:1)
根据您的代码,您似乎只存储了一张&#34;卡&#34;减速机中的物体。你应该将它存储为&#34; card&#34;反而是对象。
我假设您的减速机看起来像这样
const card = (state = null, action) => {
switch(action.type) {
case 'STORE_CARD':
return {
action.payload.data
},
...
}
}
如果以上情况属实,则每个操作都会覆盖卡片对象。而是将卡对象数据存储为对象列表,其中cardId为关键字:
const cards = (state = null, action) => {
switch(action.type) {
case 'STORE_CARDS':
return {
...state,
[action.payload.data.cardId]: action.payload.data
},
...
}
}
然后,在您的组件中:
render() {
return (
<div className='card'>
<div className='card-image-container'>
<div className='card-image' style = {{backgroundImage: `url(${this.props.rendition[this.props.cardId].url})`}}/>
</div>
</div>
);
}