Render a functional component after fetching data from a POST API?

爷,独闯天下 提交于 2021-01-29 19:52:40

问题


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}/>)}
    </>);
}

It's good to say:

  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?


回答1:


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} />)}
    </>
  );
}


来源:https://stackoverflow.com/questions/65864963/render-a-functional-component-after-fetching-data-from-a-post-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!