【发布时间】:2018-05-28 10:33:49
【问题描述】:
我的应用成功获取 API 数据并将其放入 Redux 状态树。
{
"coord":{
"lon":-0.13,
"lat":51.51
},
"weather":[
{
"id":311,
"main":"Drizzle",
"description":"drizzle rain",
"icon":"09d"
},
{
"id":501,
"main":"Rain",
"description":"moderate rain",
"icon":"10d"
}
],
//--------
//--------
"id":2643741,
"name":"London",
"cod":200
}
Props.data 已传递给组件,但实际上我只能访问
first key。例如props.data.name、props.data.id 是可访问的。但是props.data.coord.lon
和props.data.weather.map(---),未定义。
请问,我对使用 API 数据集的理解有什么问题?
组件
export const DayItem = (props) => {
return (<MuiThemeProvider>
<Paper zDepth={2}>
{props.data.coord.lon} // No way!
{props.data.name} // OK!
</Paper>
</MuiThemeProvider>)}
获取数据并调度操作的 Saga。将数据放入 Redux 存储。
function* getPosition() {
const getCurrentPosition = () => new Promise(
(res, rej) => navigator.geolocation.getCurrentPosition(res, rej))
// Gets user's current position assigned to const
const pos = yield call(getCurrentPosition);
const {latitude, longitude} = pos.coords;
// Yields the forecast API by user coordinates
const data = yield call(getForecastByCoords, latitude, longitude)
// Yields user's local forecast to the reducer
yield put({
type: LOAD_DATA_SUCCESS,
data
});
}
还有 mapStateToProps
function mapStateToProps(state) {
return {
chips: state.chipsReducer,
data: state.dataReducer
}
};
数据减速器
export const dataReducer = (state = {}, action) => {
switch (action.type) {
case LOAD_DATA_SUCCESS:
return action.data;
default:
return state;
}
};
【问题讨论】:
-
我认为如果您发布试图获取此数据的组件以及 redux 存储/操作可能会有所帮助。
-
还有
mapStateToProps函数 -
我们能看到
state.dataReducer吗? -
我猜,我的 dataReducer 有问题。但我尝试保存整个 API 对象,然后检索数据。
-
考虑到 Dan Abramov 对 Redux 的一般建议:“状态应该是可序列化的”,我试图确保从天气 API 对象收到的数据是 JSON 安全的。并尝试了 Kyle Simpson 的模式:
const data = yield JSON.parse(JSON.stringify(result))beforeyield put({ type: LOAD_DATA_SUCCESS, data })遗憾的是,没有任何改变。我只能访问第一个键,例如props.data.name但props.data.coord.lat//未定义。请问,这是怎么回事?