从对象数组访问单个对象的值React Native

时间:2020-01-09 16:24:58

标签: javascript arrays react-native object react-hooks

尝试访问数组中对象的某些值时遇到问题,该数组是我从Axios Get方法获得的响应。

我想分别访问数组每个对象的id,dateTime,sensorData之类的值,如result [0] .id(dateTime,sensorData等)。

部分代码:

const ShowSensorsScreen = ({ navigation }) => {
    const [ result, setResult ] = useState([]);
    const id = navigation.getParam('id');

    useEffect(() => {
        getResult(id);
    }, []);

    const getResult = async id => {
        const response = await searchApi.get(`/sensorData/${id}`);
        setResult(response.data);
    };
    
    console.log(result[0]);
    return (
        <ImageBackground source={backgroundImage} style={styles.ImageBackground}>
            <Bar>
                <Text style={styles.textStyle}>
                    {result[0].dateTime}
                </Text>
            </Bar>
            <SensorsDetail  evaluation={result} />
        </ImageBackground>
    );
};

使用console.log(result)甚至console.log(result [ index ])一切都很好,但是尝试使用result [0] .id会收到一条错误消息,指出未定义不是对象...

console.log中的样本(结果):

Array []
Array [
  Object {
    "sensorData01": "100.00000",
    "sensorData02": "101.00000",
    "sensorData03": "102.00000",
    "sensorData04": "103.00000",
    "dateTime": "2020-01-06T23:10:56Z",
    "id": 1,
    "idEvaluation": 1,
  },
  Object {
    "sensorData01": "110.00000",
    "sensorData02": "111.00000",
    "sensorData03": "112.00000",
    "sensorData04": "113.00000",
    "dateTime": "2020-01-06T23:11:16Z",
    "id": 2,
    "idEvaluation": 1,
  },
]

然后从console.log(result [0]):

undefined
Object {
  "dadosSensor01": "100.00000",
  "dadosSensor02": "101.00000",
  "dadosSensor03": "102.00000",
  "dadosSensor04": "103.00000",
  "dataHora": "2020-01-06T23:10:56Z",
  "id": 1,
  "idAvaliacao": 1,
}

我要感谢我能为此提供的任何帮助!

2 个答案:

答案 0 :(得分:0)

问题是setResult(挂钩)是异步的,并且您在设置状态之前正在打印result.data。设置正确的数据后,请尝试以下方法进行打印。

React.useEffect(() => {
    console.log(result[0]);
  }, [result]);

const searchApi = async (searchAppointment) => {
       console.log('Searching appointment...');
       setIsLoading(true);
       try {
               const response = await baseURL.get(
                   `/sensorsData/${searchAppointment}`);
           console.log(response.data[0]);
           setResult(response.data);
           console.log(result[0])
       } catch (err) {
           console.log(err);
           setErrorMessage('Something went wrong, please try again later...');
       }
       setIsLoading(false);
   };

请参考useState回调-useState callbacks

答案 1 :(得分:0)

所以我从另一篇文章中得到了帮助,结果发现要做到我需要做的事,我不得不使用 .map(),它是这样的:

    const sensor01 = avaliacao.map((item) => item.dadosSensor01);
    const sensor02 = avaliacao.map((item) => item.dadosSensor02);
    const sensor03 = avaliacao.map((item) => item.dadosSensor03);
    const sensor04 = avaliacao.map((item) => item.dadosSensor04);

如果还有其他更好的方式,我很想听听,谢谢大家的大力支持!