簡體   English   中英

我不能 output 來自 json 的數據

[英]I can't output data from json

我正在堆棧上開發一個網站:React,redux,typescript。我不能 output 嵌套數組,其中數據來自 JSON 中的數據 object 我的代碼:

應用程序.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;

商店/index.ts

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

減速器/index.ts

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

export type RootState = ReturnType<typeof rootReducer>

減速機/taskReducer.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: 'Произошла ошибка при загрузке данных'
            })
        }
    }
}

類型/task.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

使用類型選擇器.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 文件。

我可以 output sub 之前的所有數據,而 output 之后我不能。 我需要 output 來自 json 的所有數據。

inte.net 上試了很多方法都沒有成功

這是如何將嵌套的 object 轉換為單個數組的解決方案,請在您的代碼中這樣使用:

它將像遞歸 function 一樣工作。

 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);

我認為您缺少的是 object.keys 的用戶:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

它允許您返回 object 的鍵數組,您可以在 map 上使用這些鍵。

我的建議是做這樣的事情:

 const GanttContainer: 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 (.... {Object.keys(tasks).map((taskKeys, id) => { return ( <div key={id}> {tasks[taskKeys]} </div>).... ); }; export default GanttContainer;
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM