从Redux映射对象数据
问题描述:
试图映射从promise中返回的对象,我使用react-router 4和redux,redux-promise。数据已作为承诺返回,但我似乎无法映射它。如果我没有记错,那么render()将返回renderBanner函数并将其呈现在那里,但我有点不确定如何映射这些数据,因为我只想抓住img并将其映射。从Redux映射对象数据
编辑:例如(使用不同的API,但相同的处理)
组件文件
import React, { Component } from 'react';
import { Grid, Image } from 'react-bootstrap';
// import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { fetchAdverts } from '../actions/adverts_action';
class FullWidthBannerAd extends Component {
componentDidMount(props) {
this.props.fetchAdverts();
}
constructor(props) {
super(props)
// this.state = {
// data: []
// };
console.log('Props Contains:', props);
};
renderBanner(props) {
console.log('renderBanner Contains:', props);
return (
<div>
hello
</div>
)
}
render() {
return (
<Grid>
{this.renderBanner()}
</Grid>
);
}
}
function mapStateToProps(state) {
return {
adverts: state.adverts
};
}
export default connect(fetchAdverts)(FullWidthBannerAd);
承诺返回
[,…]
0
:{_id: "57bf06e2ad5f52130098ae1c", sort_order: null, img: "e670cf43-9ed7-45f4-987d-d899af472f4c.jpg",…}
_id:"57bf06e2ad5f52130098ae1c"
img:"e670cf43-9ed7-45f4-987d-d899af472f4c.jpg"
答
import React, { Component } from 'react';
import { Grid, Image } from 'react-bootstrap';
// import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { fetchAdverts } from '../actions/adverts_action';
class FullWidthBannerAd extends Component {
constructor(props) {
super(props)
// this.state = {
// data: []
// };
console.log('Props Contains:', props);
};
componentDidMount() {
console.log(this.props);
this.props.fetchAdverts();
}
renderBanner() {
console.log('renderBanner Contains:', this.props);
return (
<div>
hello
</div>
)
}
render() {
return (
<Grid>
{this.renderBanner()}
</Grid>
);
}
}
将您的代码更改为此。希望这会帮助你
+0
删除道具参数,它带来了,但我有一个映射问题,当我console.log this.props。有效载荷我得到[[PromiseValue]]然后我的数据有3个对象0,1,2里面有一个图像属性,我正在试图获取。我如何通过[[PromiseValue]]映射如果我尝试console.log数据与this.props.payload.data它回来undefined –
所以你的承诺返回的数据是一个包含对象的数组,每个对象都有你想要得到的图像? – Gayane
是的,这是正确 –
在你的渲染()你可以检查是否this.props.data,调用返回renderBanner,如果不返回null,并在renderBanner函数中一切正确,你可以返回
–
Gayane