开发者问题收集

TypeError:元素不可迭代

2021-09-08
1024

我正在使用 Rect/Redux,我想将一个数组转换为一个子树,就像这里解释的那样 将一个连接元素数组转换为一棵树 。 当我想访问状态并登录到控制台时, connections elements 数组都是未定义的。 error

操作

import {
  ADD_CONNECTION,
  ADD_ELEMENT,
  SAVE_DATA,
} from './types';
 
export const addElement = (node) => (dispatch) => {
  dispatch({
    type: ADD_ELEMENT,
    payload: node,
  });
};
 
export const addConnection = (edge) => (dispatch) => {
  dispatch({
    type: ADD_CONNECTION,
    payload: edge,
  });
};
 
export const saveData = (elements, connections) => (dispatch) => {
  const nodesWithoutEdges = [...elements].filter((e) => e.type);
  const map = new Map(
    nodesWithoutEdges.map((elt) => [elt.id, { ...elt, children: [] }])
  );
  for (const { source, target } of connections)
    map.get(source).children.push(map.get(target));
  //const tree = [...map.values()].filter(node => node.children.length);
  const tree = [...map.values()];
  const payload = JSON.stringify(tree);
 
  dispatch({
    type: SAVE_DATA,
    payload,
  });
};

Reducer

import * as types from '../actions/types';
 
const initialState = {
  elements: [],
  connections: [],
  data: [],
  currentElement: undefined,
};
 
const flow = (state = initialState, action) => {
  switch (action.type) {
    case types.ADD_CONNECTION:
      return {
        ...state,
        connections: state.connections.concat(action.payload),
      };
    case types.ADD_ELEMENT:
      return {
        ...state,
        elements: state.elements.concat(action.payload),
      };
    case types.SAVE_DATA:
      return {
        ...state,
        data: action.payload,
      };
    default:
      return state;
  }
};
 
export default flow;

导航栏 CTA

import React from 'react';
 
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { saveData } from '../../redux/actions/flow';
 
const NavigationBar = ({ elements, connections, saveData }) => {
  const handleCLick = () => {
    console.log('elements: ', elements); // undefined
    console.log('connections: ', connections); // undefined
    saveData(elements, connections);
  };
 
  return (
    <>
      <Navbar>
              <Button
                onClick={() => handleCLick()}
              >
                Save
              </Button>
      </Navbar>
    </>
  );
};
 
NavigationBar.propTypes = {
  saveData: PropTypes.func.isRequired,
  elements: PropTypes.object.isRequired,
  connections: PropTypes.object.isRequired,
};
 
const mapStateToProps = (state) => ({
  elements: state.elements,
  connections: state.connections,
});
 
export default connect(mapStateToProps, { saveData })(NavigationBar);
1个回答

从您商店的附件图片中,我可以看到您有多个组合的 Reducer

您的商店: 在此处输入图片说明

因此 elements 位于 flow Reducer 下,您首先需要访问该 Reducer 以获取 elements。

在您的 Navbar CTA 中:

const mapStateToProps = (state) => ({
  elements: state.flow.elements,  //<-- Here access flow first
  connections: state.flow.connections,  //<-- Also here
});
Ryan Le
2021-09-08