【问题标题】:Getting an array from the redux store puts it inside another array从 redux 存储中获取一个数组将其放入另一个数组中
【发布时间】:2018-05-01 10:36:16
【问题描述】:

所以我正在做的事情如下:

一个动作从一个 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] 来解决这个问题,但我不喜欢这样。 是什么导致我最初的 Pilots 数组被包裹在另一个数组中?

非常感谢您的帮助!

编辑:添加reducer的代码。

【问题讨论】:

  • 你能分享你的reducer代码吗?
  • 我在原来的问题中添加了减速器代码。

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


【解决方案1】:

由于pilots也是一个数组,所以你也需要散布它。

代替

return [
  ...state,
  action.pilots
]

将您的新状态返回为

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

【讨论】:

  • @Gwouten 总是乐于提供帮助:)
【解决方案2】:

在reducer内部使用扩展运算符时出错

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

应该是

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

【讨论】:

  • 也谢谢你!
【解决方案3】:

这是我在 reducer 中的状态

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] 
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    相关资源
    最近更新 更多