简体   繁体   中英

Rendering nested data (objects from an array inside an object of another array ) From backend - ReactJS (JSX)

I have JSON data i am trying to render to the front end of my application. and I am trying to get the name of all the objects inside the betTypes array to the front end as a List. So far, I am only able to query a single object from the nested array.

const data = {
  games: [
    {
      name: 'BlackJack',
      slug: 'American Blackjack',
      category: 'Card games',
      image: '/images/bj.jpg',
      betTypes: [
        {
          name: 'Flush',
          det: 'Flush',
          category: 'American Blackjack',
          description:
            'The player’s two initial cards and dealer’s first cards are all of the same suits and have different values (it is also valid if two of the three cards are of the same value)',
          image: '',
        },
        {
          name: 'Mixed Color Pair',
          det: 'MXP',
          category: 'American Blackjack',
          description:
            'When the player gets two initial cards as a pair (same value) of different colour and different suit.',
          image: '',
        },
      ],
    }, 
},

This is what my front-end code looks like

function GameScreen() {
  const params = useParams();
  const { slug } = params;

  const [{ loading, error, game }, dispatch] = useReducer(reducer, {
    game: [],
    loading: true,
    error: '',
  });
  // const [games, setGames] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'FETCH_REQUEST' });
      try {
        const result = await axios.get(`/api/games/slug/${slug}`);
        dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
      } catch (err) {
        dispatch({ type: 'FETCH_FAIL', payload: err.message });
      }

      //setGames(result.data);
    };
    fetchData();
  }, [slug]);

  return loading ? (
    <div>
      <LoadingSpin />
    </div>
  ) : error ? (
    <div>{error}</div>
  ) : (
    <div>
      <Row>
        <Col md={12}>
          <h1>{game.name}</h1> <hr />
          <img className="img-large" src={game.image} alt={game.name} />
        </Col>
        <Col md={3}>
          <ListGroup>
            <ListGroup.Item style={{ marginTop: '10px' }}>
              <h6>{game.betTypes[3].name}</h6>
            </ListGroup.Item>
          </ListGroup>
        </Col>
        <Col md={3}></Col>
      </Row>
    </div>
  );
}

I need help sorting it out please.

    <ListGroup>
         {game.betTypes.map((item)=>
            <ListGroup.Item key={item.name} style={{ marginTop: '10px' }}>
                <h6>{item.name}</h6>
            </ListGroup.Item>)
         }
    </ListGroup>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM