从redux存储中获取数组会将其放入另一个数组

时间:2017-11-17 15:37:41

标签: reactjs redux react-redux fetch redux-thunk

所以我正在做的是以下内容:

操作从URL获取.json文件并调度另一个操作。 pilots的值为[Array(278)]

export const pilotsFetchDataSucces = (pilots) => {
  return {
    type: 'PILOTS_FETCH_DATA_SUCCES',
    pilots
  }
};

export const pilotsFetchData = (url) => (dispatch) => {
  fetch(url)
  .then((response) => {return response.json()})
  .then((pilots) => {
    dispatch(pilotsFetchDataSucces(pilots))
  })
  .catch((e) => {console.log('Error in pilotsFetchData', e)});
};

这是减速器:

const pilotsReducer = (state = [], action) => {
  switch(action.type){
    case 'PILOTS_FETCH_DATA_SUCCES':
    console.log('pilotsReducer', action.pilots);
    return [
      ...state,
      action.pilots
    ];

    default:
    return state;
  }
}

export default pilotsReducer;

稍后在我的组件中,我想访问这些数据。我正在使用mapStateToProps。

import React from 'react';
import { connect } from 'react-redux';
import SinglePilot from './SinglePilot.js';
import { pilotsFetchData } from '../actions/pilots';

class Pilots extends React.Component {

  componentDidMount () {
 this.props.fetchData('https://raw.githubusercontent.com/guidokessels/xwing-data/master/data/pilots.js');
  }

  render(){
    return (
      <div>
        <h1>Title</h1>
        {this.props.query && <p>You searched for: {this.props.query}</p>}
        {
          //iterate over all objects in this.props.pilots
          this.props.pilots.map( (pilot) => {
            return (
            <SinglePilot
              key={pilot.id}
              name={pilot.name}
           />
          )})
        }
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
      pilots: state.pilots // is [[Array(278)]] instead of [Array(278)]
    });

const mapDispatchToProps = (dispatch) => ({
  fetchData: (url) => dispatch(pilotsFetchData(url))
});

export default connect(mapStateToProps, mapDispatchToProps)(Pilots);

我遇到的问题是state.pilots的值现在是一个长度为1的数组,而我想要的数组(长度为278)就在这个数组中。

我知道我可以使用state.pilots[0]解决此问题,但我不喜欢这样。 是什么导致我的初始导频数组被包装在另一个数组中?

非常感谢您的帮助!

编辑:添加了reducer的代码。

3 个答案:

答案 0 :(得分:1)

由于pilots也是一个数组,你也需要传播它。

而不是

return [
  ...state,
  action.pilots
]

将您的新状态恢复为

return [
  ...state,
  ...action.pilots
]

答案 1 :(得分:0)

在reducer

中使用spread运算符时出错
return [
      ...state,
      action.pilots
    ];

应该是

return [
      ...state,
      ...action.pilots
    ];

答案 2 :(得分:0)

这是我在减速器中的状态

const initialState = {
    loading: false,
    employee: [],
    error: ''
}

这是减速器

export default function contactData(state = initialState,action)
{
    switch(action.type){
        case FETCH_EMPLOYEE_SUCCESS :
            console.log(state)
            console.log(action.data)
            return {
                ...state,
                 employee:[...state.employee,...action.data]    //correct way to copy action data to employee array in state
            }

            case FETCH_EMPLOYEE_FAIL :
                return {
                    ...state,
                    loading:false,
                    error:action.error
                }

                default:
                    return state
    }
}

action.data中的数据

action.data = {[
  {
    "id": 1,
    "name": "Leanne Graham",
    "email": "Sincere@april.biz",
    "phone": "1-770-736-8031 x56442",
    "company": {
      "name": "Romaguera-Crona"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "email": "Shanna@melissa.tv",
    "phone": "010-692-6593 x09125",
    "company": {
      "name": "Deckow-Crist"
    }
  }]}

所以这个action.data也是一个数组,所以当我想将action.data中的数组类型数据放入员工数组时,我们这样做

return {
               ...state,   
                 employee:[...state.employee,...action.data] 
            }