反应状态形状中不需要的嵌套级别(处理JSON时)

时间:2017-12-22 17:00:08

标签: json redux fetch axios

我刚开始玩React \ Redux(但没有R \ R问题)。我试图映射一些从服务器api获取它的实体,但是当我得到它们时 - 它们会自动包裹在更深的阵列级别而我无法将它们排除在外。这是我的代码片段。我认为没有什么不寻常之处:

import { getGroupList } from './actions/groupActions';

class GroupContainer extends Component {
 constructor (props){
    super(props);
 };


componentWillMount = function(){
  fetch('http://localhost:3000/groups.json')
    .then( (response) => {
      return response.json()
  })
    .then((json) => {
      return json.groups;
  })
    .then((result) => {
      this.props.onGetGroupList(result); //call action
  })
 };

render() {
    return (
        <div className="groups">
        { 
          this.props.groups.map( (group, index) => 
          { 
            return <Link key={index} to={`/group/${index}`} >
            <div id={index}><p>{group.name}</p></div></Link> 
          })
        }
        </div>
    );
  }

}

const mapStateToProps = (state) =>{
  return {
    groups: state.groups
  }
};

const mapDispatchToProps = (dispatch)  =>{
  return {
    onGetGroupList: (items) => dispatch(getGroupList(items))
  }
};


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

// reducers / groups.js ...我将跳过combineReducers,动作创建者 - 没有什么有趣的

const initialState = [];

export default function groups(state = initialState, action) {
  switch (action.type) {
    case 'GROUP_LIST_SUCCESS':
    console.log(action);
      return [
        ...state,
        action.payload
      ];

    default:
      return state;
  }
}

我的groups.json文件是:

{
  "groups": [{
      "name": "FIRST GROUP" 
    },
    {
      "name": "SECOND GROUP" 
    } 
  ]
}

在ReduxDevTools中,我在实体上看到了额外的嵌套级别 - &#34; 0&#34; the group entities with additional nesting level

这就是为什么地图功能不能迭代群组项目的原因。正如你在上面所看到的,我还有另外一套 - &#39;工会&#39;没有额外的嵌套。 Unions设置为我的其他组件reducer的initialState:

const initialState = [
  unions = {
    name: 'Some name',
    interval: '1-8.',
    father: '0'
  },
  {
    name: 'Some other name',
    interval: '1-11',
    father: '0'
  } 
   .....
];

export default function unions(state = initialState, action) {.....}

我对渲染联盟组件没有任何问题。所以我的一般问题 - json解析(或其他什么)的问题是什么?我尝试使用axios而不是原生取物 - 结果相同。我试图 JSON.parse(&#39; {   &#34; groups&#34;:[{       &#34; name&#34;:&#34; FIRST GROUP&#34;     },     {       &#34; name&#34;:&#34; SECOND GROUP&#34;     }   ] }&#39;)取而代之的是网页,没有运气。我总是在数据的形状中得到一个更深层次的嵌套级别。请帮忙。

稍后添加... /action/groupActions.js     / *      *动作创作者      * /

export function getGroupList(items) {
  console.log('groups_action_creator:',items);
  return {
    type: 'GROUP_LIST_SUCCESS',
    payload: items
  }
};

1 个答案:

答案 0 :(得分:1)

只是为了进一步搜索。如果我被困在api的简单抓取中,也许它会节省一些人的时间。事情发生在我用有效载荷推回新状态时。当我console.log整个reducer返回时,我能够看到内部redux包装: [].concat(_toConsumableArray(state), [action.payload]) 我在搜索redux文档,但没有找到内部设计的解释。但它指出我找到解决问题的方法。

最后,我将reducer修改为:

const initialState = [];
export default function groups(state = initialState, action) {
  switch (action.type) {
    case 'GROUP_LIST_SUCCESS':
    // make new object from state and payload. No mutations here
    let newStateObject = Object.assign({}, state, action.payload);
    // convert the shape of new state to array, so i can iterate it later with map function
    let newStateArray = Array.from(Object.keys(newStateObject), k => newStateObject[k]);
      return newStateArray;
    default:
      return state;
  }
}
相关问题