Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

javascript - Render a functional component after fetching data from a POST 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}/>)}
    </>);
}

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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...