You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从含多数组的JSON发布信息?flightData未定义问题排查

Hey there, let's break down this problem and fix it step by step! The "flightData undefined" and missing "Loading..." messages point to issues in how your Redux data flow is set up, so let's start with the most common culprits.

First, Check Your Action Creator (Async Handling)

If you're fetching data asynchronously, you need to use middleware like redux-thunk to handle the async logic, and dispatch proper loading/success/failure actions. Let's make sure your action is structured correctly:

// Example action creator with thunk
export const fetchFlightData = () => {
  return async (dispatch) => {
    // Dispatch a "request" action to trigger loading state
    dispatch({ type: 'FETCH_FLIGHT_REQUEST' });
    
    try {
      const response = await fetch('http://localhost:3001/api');
      if (!response.ok) throw new Error('Request failed');
      
      const rawData = await response.json();
      // Extract your target arrays
      const { Agents, Itinerarie, Legs, Segments } = rawData;
      
      // Dispatch success with the filtered data
      dispatch({
        type: 'FETCH_FLIGHT_SUCCESS',
        payload: { Agents, Itinerarie, Legs, Segments }
      });
    } catch (err) {
      // Dispatch failure if something goes wrong
      dispatch({
        type: 'FETCH_FLIGHT_FAILURE',
        payload: err.message
      });
    }
  };
};

Next, Fix Your Reducer's Initial State & Logic

Your reducer is likely missing a proper initial state (which is why flightData is undefined) or not updating state correctly. Here's a corrected version:

// Initial state with loading, flightData, and error
const initialState = {
  loading: false,
  flightData: {
    Agents: [],
    Itinerarie: [],
    Legs: [],
    Segments: []
  },
  error: null
};

const flightReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'FETCH_FLIGHT_REQUEST':
      return {
        ...state,
        loading: true,
        error: null // Reset error on new request
      };
    case 'FETCH_FLIGHT_SUCCESS':
      return {
        ...state,
        loading: false,
        flightData: action.payload // Update with the filtered arrays
      };
    case 'FETCH_FLIGHT_FAILURE':
      return {
        ...state,
        loading: false,
        error: action.payload
      };
    default:
      return state; // Always return default state for unrecognized actions
  }
};

export default flightReducer;

Verify Your Container/Component Setup

Make sure your component is correctly connected to Redux, and you're using the loading state properly:

import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchFlightData } from './path-to-your-actions';

const FlightComponent = ({ loading, flightData, error, fetchFlightData }) => {
  // Trigger data fetch on component mount
  useEffect(() => {
    fetchFlightData();
  }, [fetchFlightData]);

  // Show loading first
  if (loading) return <div>Loading...</div>;
  
  // Show error if request failed
  if (error) return <div>Error: {error}</div>;

  // Now flightData should be defined
  console.log("I AM HERE NOW", flightData);
  
  return (
    <div>
      {/* Render your Agents/Itinerarie/Legs/Segments here */}
    </div>
  );
};

// Map Redux state to component props
const mapStateToProps = (state) => ({
  loading: state.flight.loading, // Match your reducer's path in the store
  flightData: state.flight.flightData,
  error: state.flight.error
});

// Map dispatch actions to props
const mapDispatchToProps = {
  fetchFlightData
};

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

Final Checks

  1. Redux Middleware: Ensure your store is configured with redux-thunk to handle async actions:
    import { createStore, applyMiddleware, combineReducers } from 'redux';
    import thunk from 'redux-thunk';
    import flightReducer from './path-to-your-reducer';
    
    const rootReducer = combineReducers({
      flight: flightReducer // This is the path used in mapStateToProps
    });
    
    const store = createStore(rootReducer, applyMiddleware(thunk));
    export default store;
    
  2. Network Request: Check your browser's Network tab to confirm the request to http://localhost:3001/api is succeeding (no 404/CORS errors). If the request fails, your reducer will hit the failure case instead of success.

内容的提问来源于stack exchange,提问作者S. N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 06:17:40