如何在我的对象(Redux,React)中获取(我的api json)数据?

时间:2018-04-22 00:15:07

标签: json reactjs redux

我没有用javascript等来解决所有问题,我想通过ma action redux返回我的数据,但我的代码有问题。

const mapStateToProps = state => {
    const group = state.groupReducer.group ? state.groupReducer.group  : [ ]
    return {
        group
    }

我如何获取我的数据?

x

当我尝试时:

const mapStateToProps = state => {
    const group = state.groupReducer.group.data.data[0] ? state.groupReducer.group.data.data[0]  : [ ]
    return {
        group
    }

x

我的目标是group

    renderGroup = group => {
    return group.map((groups => {
        <div key={groups.data.data.id}>
        //
        </div>
    }))
}

Sagas.js

 export function* loadApiDataGroup() {
  try {
  // API 
    const response = yield 
    call(axios.get,'http://localhost:8000/api/group');
    yield put(loadGroup(response))
    } catch (e) {
      console.log('REQUEST FAILED! Could not get group.')
     console.log(e)
     }
      }

Action.js

 export function loadGroup(data){ return { type: LOAD_GROUP, data }};
 export function creatGroup(data){ return { type: CREATE_GROUP, data}};

// reducer

     export default function groupReducer( state= {}, action = {}){
     switch (action.type){
      case LOAD_GROUP:
        return {
            ...state,
            group: action.data
        }
     case CREATE_GROUP:
        return {
            ...state
        }
    default:
        return state
}

谢谢你帮助我

1 个答案:

答案 0 :(得分:0)

尝试

const mapStateToProps = state => ({
    group: state.groupReducer.group || []
});

然后您可以在组件中使用this.props.group。即使你可能只想要mapStateToProps中的一件事,它通常也不会像那样直接返回。

如果group是API请求的响应,则需要首先解压缩data,这是在您的异步操作创建者中完成的(您将需要使用redux-thunk或类似的东西):

const getGroup = () => async (dispatch) => {
    dispatch({ type: 'GET_GROUP_REQUEST' });
    try {
        const { data } = await axios.get('/some/url');
        dispatch({ type: 'GET_GROUP_SUCCESS', payload: data });
    } catch (error) {
        dispatch({ type: 'GET_GROUP_FAILURE', payload: error });
    }
};