简体   繁体   中英

How to get values from array using index value

I am trying to get values from a list using index value via for loop. but after getting and assigning them to another list it shows all values are undefined. How to solve this

import React, { useEffect, useContext, useState } from 'react';
import { useHistory } from 'react-router-dom';

function Function() {
  const history = useHistory();

  const [data, setData] = useState({});
  const [features, setFeatures] = useState({});
 
  useEffect(() => {
    const passingData = history.location.state; //array passed from prev page
    setData(passingData);
    console.log(data);//log=> {'id':01 ,'name':"name1"},{'id':02 ,'name':"name2"},{'id':03 ,'name':"name3"}

    const tFeatures = [];
    for (var i = 0; i < 2; i++) {
      tFeatures.push(data[i]);
     }
    console.log(tFeatures);//output => [undefined, undefined, undefined]
  }, []);


  return <div></div>;
}

export default Function;
console.log(data); // {'id':01 ,'name':"name1"},{'id':02 ,'name':"name2"},{'id':03 ,'name':"name3"}
console.log(tFeatures) // [undefined, undefined, undefined]

Why don't you use passingData instead of data ? By the time you call console.log(data) , it won't have been set yet (it's asynchronous). So either use passingData or extract the part that depends on data and put it in its own useEffect() .

function Function() {
    const history = useHistory();

    const [data, setData] = useState([]); // should be an array, not an object
    const [features, setFeatures] = useState([]); // should be an array, not an object

    useEffect(() => {
        const tFeatures = [];
        for (var i = 0; i < 2; i++) {
            tFeatures.push(data[i]);
        }
    }, [data])

    useEffect(() => {
        const passingData = history.location.state;
        setData(passingData);
    }, [history.location.state]);


    return <div></div>;
}

or

function Function() {
    const history = useHistory();

    const [data, setData] = useState([]); // should be an array, not an object
    const [features, setFeatures] = useState([]); // should be an array, not an object

    useEffect(() => {
        const passingData = history.location.state;
        setData(passingData);
        const tFeatures = [];
        for (var i = 0; i < 2; i++) {
            tFeatures.push(passingData[i]); // use passingData not data
        }
    }, [history.location.state]);


    return <div></div>;
}

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