【发布时间】:2016-09-30 11:44:55
【问题描述】:
我正在从 REST 服务检索数据。数据以数组形式返回。这是我用来检索数据的函数。
export function fetchMessage() {
return function(dispatch) {
axios.get(`${ROOT_URL}/currencies`, {
headers: { token: localStorage.getItem('token') }
})
.then(response => {
console.log(response.data);
dispatch({
type: FETCH_MESSAGE,
payload: response.data
});
});
}
}
fetchMessage 的输出是一个对象数组。
[Object, Object, Object, Object, Object, Object]
0:Object
addedDate:"2013-08-22"
ccyCode:"CHF"
country:"SCHWIZER FRANC"
lastChangeDate:"2016-05-02"
offerRate:7.02
prevRate:8.501
prevRateDate:"2016-04-01"
rate:8.425
rateDate:"2016-05-01"
unit:1
__proto__:Object
1:Object
2:Object
3:Object
4:Object
5:Object
fetchMessage 函数被下面的组件调用。
class Feature extends Component {
componentWillMount() {
this.props.fetchMessage();
//console.log(this.props);
}
render() {
return (
<div>{this.props.message}</div>
);
}
}
function mapStateToProps(state) {
return { message: state.auth.message };
}
export default connect(mapStateToProps, actions)(Feature);
组件无法呈现消息,因为它是一个
bundle.js:1256 Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {ccyCode, country, unit, rateDate, rate, prevRateDate, prevRate, offerRate, addedDate, lastChangeDate}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Feature`.(…)
我试图像这样运行this.props.message 的地图
<div>
{this.props.message.map(
function(object){
return ('Something'
);
}
)}
</div>
但我收到一条错误消息,提示我无法在 message 上运行 map。如何渲染对象中的数据?我需要以其他方式保存它吗?如何遍历对象以呈现它们?
【问题讨论】:
-
试试这样的:
<div>{this.props.message.ccyCode} {this.props.message.rate}</div>然后从那里开始。 -
@ChrisG 我尝试了
<div>{this.props.message.ccyCod}</div>和<div>{this.props.message.rate}</div>并且都给出了错误消息Uncaught TypeError: Cannot read property 'rate' of undefined当我尝试使用ccyCode时,未定义的属性当然会更改为ccyCode。
标签: javascript reactjs react-redux redux-thunk