我试图解析从外部api收到的json。
我的减速机是:
import { RECEIVED_FORECAST } from '../actions/index';
export default function ForecastReducer (state = [], action) {
switch (action.type) {
case RECEIVED_FORECAST:
return Object.assign({}, state, {
item: action.forecast
})
default:
return state;
}
}
然后主减速器就像:
import { combineReducers } from 'redux';
import ForecastReducer from './forecast_reducer';
const rootReducer = combineReducers({
forecast: ForecastReducer
});
export default rootReducer;
和容器看起来像
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
class WeatherResult extends Component {
render() {
const forecast = this.props.forecast.item;
{console.log('almost: ', forecast)}
return (
<div>
<h1> </h1>
</div>
)
}
}
function mapStateToProps({ forecast }) {
return {
forecast
}
}
export default connect(mapStateToProps)(WeatherResult)
几乎的输出与我想的完全相同:
almost:
Object
currently: {time: 1476406181, summary: "Drizzle", icon: "rain", nearestStormDistance: 0, precipIntensity: 0.0048, …}
daily: {summary: "Light rain on Saturday and Thursday, with temperatures rising to 92°F on Wednesday.", icon: "rain", data: Array}
所以,我的问题是,我怎样才能显示出来的价值,让我们说一下Forecast.currently.summary?
1)如果我只是尝试将其插入{}我收到:&#39; TypeError:undefined不是对象(评估&#39; forecast.currently&#39;)&#39;
2)我无法使用映射,因为json可能添加了其他组件
是否有任何方法可以直接获取此属性,而无需映射所有文件?
由于
答案 0 :(得分:0)
您遇到的问题是您正在请求数据。这不会立即完成。想想在等待天气数据到达时应用程序正在做什么。
它正在展示一些东西。在您的情况下,渲染方法失败,因为您正在尝试显示尚未到达的数据。
解决方案:
render() {
const forecast = this.props.forecast;
const text = forecast && forecast.item.currently.summary || 'loading...';
return (
<div>
<h1>{text}</h1>
</div>
)
}
}
通过这种方式,您可以检查是否已有数据,如果没有,则显示有用的内容。