reactjs 我无法从json输出数据

ego6inou  于 2022-11-29  发布在  React
关注(0)|答案(2)|浏览(143)

我正在开发一个网站上的堆栈:我无法在JSON中输出包含数据对象中数据的嵌套数组我的代码:
app.tsx

const App: React.FC = () => {
    const {tasks, loading, error} = useTypedSelector(state => state.task)
    const dispatch: Dispatch<any> = useDispatch()

    useEffect(() => {
        dispatch(fetchTasks())
    }, [])

    if (loading) {
        return <h1>Идет загрузка...</h1>
    }
    if (error) {
        return <h1>{error}</h1>
    }

    return (
        <div className="Gant_Container">
            <div>
                <p className="Project_Period">{Object.values(tasks)[0]} / {Object.values(tasks)[1]}</p>
            </div>
            <div>
                {Object.values(tasks).map((task, id) => {
                    return (<div key={id}>
                        {task.id}
                        {task.title}
                        {chart.start}
                        {chart.end}
                    </div>)
                })}
            </div>
        </div>
    );
};

export default Gantt_Container;

存储/索引.ts

export const store = createStore(rootReducer, applyMiddleware(thunk))

异径管/索引.ts

export const rootReducer = combineReducers({
    task: taskReducer,
})

export type RootState = ReturnType<typeof rootReducer>

减速器/任务减速器.tsx

const initialState: TaskState = {
    tasks: [],
    loading: false,
    error: null
}

export const taskReducer = (state = initialState, action: TaskAction): TaskState => {
    switch (action.type) {
        case TaskActionTypes.FETCH_TASKS:
            return {loading: true, error: null, tasks: []}
        case TaskActionTypes.FETCH_TASKS_SUCCESS:
            return {loading: false, error: null, tasks: action.payload}
        case TaskActionTypes.FETCH_TASKS_ERROR:
            return {loading: false, error: action.payload, tasks: []}
        default:
            return state
    }
}

动作创建者/task.ts

export const fetchTasks = () => {
    return async (dispatch: Dispatch<TaskAction>) => {
        try {
            dispatch({type: TaskActionTypes.FETCH_TASKS})
            const response = await axios.get("") // The data is coming from the backend, I have hidden the data
            dispatch({type: TaskActionTypes.FETCH_TASKS_SUCCESS, payload: response.data})
        } catch (e) {
            dispatch({
                type: TaskActionTypes.FETCH_TASKS_ERROR,
                payload: 'Произошла ошибка при загрузке данных'
            })
        }
    }
}

类型/任务.ts

export interface TaskState {
    tasks: any[];
    loading: boolean;
    error: null | string;
}

export enum TaskActionTypes {
    FETCH_TASKS = 'FETCH_TASKS',
    FETCH_TASKS_SUCCESS = 'FETCH_TASKS_SUCCESS',
    FETCH_TASKS_ERROR = 'FETCH_TASKS_ERROR'
}

interface FetchTasksAction {
    type: TaskActionTypes.FETCH_TASKS;
}

interface FetchTasksSuccessAction {
    type: TaskActionTypes.FETCH_TASKS_SUCCESS;
    payload: any[]
}

interface FetchTasksErrorAction {
    type: TaskActionTypes.FETCH_TASKS_ERROR;
    payload: string;
}

export type TaskAction = FetchTasksAction | FetchTasksSuccessAction | FetchTasksErrorAction

useTypedSelector.ts

export const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector

.json文件夹

{
  "name": "Project",
  "data": "2022",
  "task": {
    "id": 1,
    "title": "Apple",
    "start": "2021",
    "end": "2022",
    "sub": [
      {
        "id": 2,
        "title": "tomato",
        "start": "2021",
        "end": "2022",
        "sub": [
          {
            "id": 3,
            "title": "Orange",
            "start": "2019",
            "end": "2020",
            "sub": [
              {
                "id": 4,
                "title": "Banana",
                "start": "2022",
                "end": "2022",
                "sub": [
                  {
                    "id": 5,
                    "title": "Strawberry",
                    "start": "2015",
                    "end": "2018"
                  },
                  {
                    "id": 6,
                    "title": "cherry",
                    "period_start": "2001,
                    "period_end": "2003"
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
}

不幸的是,我不能编辑这个json文件。
sub之前的数据我都可以输出,sub之后就不能输出了,我需要把json里面的数据全部输出。
我试过很多方法从互联网上,但我没有成功
下面是执行console.log(tasks)时会发生的情况:
enter image description here
代码和框:https://codesandbox.io/p/github/vhipper/task2/draft/reverent-water?file=%2Fsrc%2FApp.tsx&workspace=%257B%2522activeFileId%2522%253A%2522clb0mcxbe000q7pfa1mst4hhi%2522%252C%2522openFiles%2522%253A%255B%2522%252FREADME.md%2522%252C%2522%252Fsrc%252Findex.tsx%2522%255D%252C%2522sidebarPanel%2522%253A%2522EXPLORER%2522%252C%2522gitSidebarPanel%2522%253A%2522COMMIT%2522%252C%2522spaces%2522%253A%257B%2522clb0mdi070010436nbga1oqu8%2522%253A%257B%2522key%2522%253A%2522clb0mdi070010436nbga1oqu8%2522%252C%2522name%2522%253A%2522Default%2520Space%2522%252C%2522devtools%2522%253A%255B%257B%2522type%2522%253A%2522PREVIEW%2522%252C%2522taskId%2522%253A%2522start%2522%252C%2522port%2522%253A3000%252C%2522key%2522%253A%2522clb0mdmag0081436n7akajuoy%2522%252C%2522isMinimized%2522%253Afalse%257D%252C%257B%2522type%2522%253A%2522TASK_LOG%2522%252C%2522taskId%2522%253A%2522start%2522%252C%2522key%2522%253A%2522clb0mdirx005c436n5ur3zsyn%2522%252C%2522isMinimized%2522%253Afalse%257D%255D%257D%257D%252C%2522currentSpace%2522%253A%2522clb0mdi070010436nbga1oqu8%2522%257D

vaqhlq81

vaqhlq811#

这是如何将嵌套对象转换为单个数组的解决方案,请在代码中使用,如下所示:
它将像递归函数一样工作。

const obj = {
  name: 'Project',
  data: '2022',
  task: {
    id: 1,
    title: 'Apple',
    start: '2021',
    end: '2022',
    sub: [{
      id: 2,
      title: 'tomato',
      start: '2021',
      end: '2022',
      sub: [{
        id: 3,
        title: 'Orange',
        start: '2019',
        end: '2020',
        sub: [{
          id: 4,
          title: 'Banana',
          start: '2022',
          end: '2022',
          sub: [{
              id: 5,
              title: 'Strawberry',
              start: '2015',
              end: '2018',
            },
            {
              id: 6,
              title: 'cherry',
              start: '2001',
              end: '2003',
            },
          ],
        }, ],
      }, ],
    }, ],
  },
};

const arr = [];

const foo = (task) => {
  if (!task.id) return;
  arr.push({
    id: task.id,
    title: task.title,
    start: task.start,
    end: task.end,
  });

  if (task.sub && task.sub.length > 0) task.sub.forEach(item => foo(item));
};

foo(obj.task);

console.log('>>>>>  arr : ', arr);
0yg35tkg

0yg35tkg2#

我认为你缺少的是对象的用户。键:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
它允许你返回一个你可以Map的对象的键数组。
我的建议是这样的:
第一个

相关问题