从 POST API 获取数据后渲染功能组件? [英] Render a functional component after fetching data from a POST API?

查看:38
本文介绍了从 POST API 获取数据后渲染功能组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在从我的 API 获取数据后重新渲染我的组件.我用钩子来处理.但它不起作用.实际上我的组件是第一次渲染,而不是在获取数据之后!

I want to re-render my component after the data fetched from my API. I used hooks to handle that. but it does not working. actually my component renders for the first time, not after fetching data!

我有一个外部函数.通过这个功能,我可以给那个省一个省名,然后接收他们在那个省的城市列表.我的功能如下:

I have an external function. By this function, I can give a province name to that and then receive a list of the cities which they are in that province. my function is like below:

const axios = require('axios');
export default async function getCities(state) {
    let res = [], err;
    try {
        await axios.post('someUrl', {
            ProvinceUser: state,
        }).then(function (response) {
            if (response.status === 200) {
                for (let i = 0; i < response.data.length; i++)
                    res.push(response.data[i].CityUser);
            }
        }).catch(function (error) {
            err = error;
        });
    } catch (error) {
        err = error;
    }
    return {
        response: res,
        error: err
    }
}


我在我的组件中使用上述函数,如下所示:


I'm using the above function in my component like below:

import React, {useEffect} from "react";
import getCities from "../functions/getCities";
import RadioList from "./RadioList";

export default function ListOfStates(props) {
    let labels = [],
        cities = [];
    useEffect(() => {
        getCities(props.cityState).then((array) => {
            for (let i = 0; i < array.response.length; i++)
                cities.push(array.response[i]);
            labels = cities;
        });
    }, []);
    return (<>
        {labels.map((labels, index) =>
            <RadioList active={(labels === props.active)} key={index} label={labels}/>)}
    </>);
}


说得好:

  1. 我在 useEffect 中使用了 console.log(labels).一切都很好带有 labels 数组.只需更新组件即可.
  2. 我在 useEffect 中使用了 labels 数组作为 deps.但它没有工作.
  1. I used console.log(labels) in useEffect. and everything is okay with labels array. just the component should be updated.
  2. I used labels array for the deps in useEffect. but it does not worked.

那么,哪些部分出了问题?

So, which parts are going wrong?

推荐答案

简单地更新变量的值不会触发渲染,但是如果您使用 useState()<将标签声明为状态数组/code> 钩子会更新它.

Simply updating the value of a variable won't trigger a render, however if you declare your labels as a state array using the useState() hook updating it will.

注意: 使用索引作为键是一种反模式,只会在以后带来麻烦,请为每个元素选择一个唯一的标识符作为键.

Note: Using index as a key is an anti-pattern which will only lead to headaches later, choose a unique identifier for each element to use as key instead.

import React, { useEffect, useState } from "react";
import getCities from "../functions/getCities";
import RadioList from "./RadioList";

export default function ListOfStates(props) {
  const [labels, setLabels] = useState([]);
  const cities = [];

  useEffect(() => {
    getCities(props.cityState).then((array) => {
      for (let i = 0; i < array.response.length; i++) {
        cities.push(array.response[i]);
      }
      setLabels([...cities]);
    });
  }, []);

  return (
    <>
      {labels.length && labels.map((labels, index) =>
        <RadioList active={(labels === props.active)} key={labels.id} label={labels} />)}
    </>
  );
}

这篇关于从 POST API 获取数据后渲染功能组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆