Openweather API每3小时提供5天的预测。我们只需要显示当天的数据。如何分隔当天的数据并仅绑定当天和当天的每个小时的数据?这是代码:
数据看起来像这样:
{
"data": {
"cod": "200",
"message": 0.0062,
"cnt": 39,
"list": [
{
"dt": 1540177200,
"main": {
"temp": 24.55,
"temp_min": 20.88,
"temp_max": 24.55,
"pressure": 1008.67,
"sea_level": 1025.96,
"grnd_level": 1008.67,
"humidity": 58,
"temp_kf": 3.67
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "02d"
}
],
"clouds": {
"all": 8
},
"wind": {
"speed": 3.82,
"deg": 340.5
},
"sys": {
"pod": "d"
},
"dt_txt": "2018-10-22 03:00:00"
},
{
"dt": 1540188000,
"main": {
...
},
},
{
"dt": 1540198800,
"main": {
...
},
},
{
"dt": 1540587600,
"main": {
. . .
}
}
]
}
Redux Saga
export const fetchWeatherListStart = () => ({
type: ActionTypes.FETCH_WEATHER_START
});
...
import { takeLatest, put } from "redux-saga/effects";
function* fetchWeatherSaga(){
try {
const weatherResponse = yield fetch("https://samples.openweathermap.org/data/2.5/forecast?lat=35&lon=139&appid=439d4b804bc8187953eb36d2a8c26a02")
const weatherlist = yield weatherResponse.json()
yield put(fetchWeatherSuccess(weatherlist));
} catch (error) {
yield put(fetchWeatherError(error.message));
}
}
export default function* watchFetchWeatherSaga(){
yield takeLatest("FETCH_WEATHER_START", fetchWeatherSaga)
}
减速器
const INITIAL_STATE = {
weatherList: null,
isFetching: false,
errorMessage: undefined
};
const fetchWeatherListReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case "FETCH_WEATHER_START":
return {
...state,
isFetching: true
};
case "FETCH_WEATHER_SUCCESS":
return {
...state,
isFetching: false,
weatherlist: action.payload
};
case "FETCH_WEATHER_ERROR":
return {
...state,
isFetching: false,
errorMessage: action.payload
};
default:
return state;
}
};
export default fetchWeatherReducer;
Component
export const WeatherPage = ({ fetchWeatherListStart}) => {
useEffect(() => {
fetchWeatherListStart();
}, [fetchWeatherListStart]);
...
我曾考虑使用选择器,但不确定这是否是最好的方法。如何解决?
您可以在减速机级别上执行此操作,唯一需要的是当前日期戳
case "FETCH_WEATHER_SUCCESS":
// pass today's date along when calling this action
const myDate = action.payload.todayDate
// get only data for today
const filteredList = action.payload.list.filter(item => item.dt === myDate)
return {
...state,
isFetching: false,
weatherlist: filteredList
};