React / Redux和API数据对象

问题描述 投票:0回答:2

我的应用程序成功获取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.nameprops.data.id是可访问的。但是props.data.coord.lonprops.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
  }
};

dataReducer

export const dataReducer = (state = {}, action) => {
  switch (action.type) {
    case LOAD_DATA_SUCCESS:
      return action.data;
    default:
      return state;
  }
};
reactjs api redux
2个回答
1
投票

最后,我明白了。问题在于React渲染与数据加载的速度差异。加载总是在渲染后面。因此,完整的数据集不存在。

只是条件渲染使我的一天{this.state.isLoading ? <div>Loading</div> : <DayItem {...this.props}/>}


-1
投票

你必须使用MapStateToProps,然后使用componentWillReceiveProps(nextProps)

像这样的东西

function mapStateToProps(state) {


    return {

      data:state.toJS().yourReducer.data,

    }

然后做下一个:

componentWillReceiveProps(nextProps) {
if (nextProps.data) {
      if (nextProps.data.coord.lon != undefined) {
        this.setState({yourData:nextProps.data.coord.lon}
      }
}
© www.soinside.com 2019 - 2024. All rights reserved.