My Code :
import Item from './Item_att.js';
import axios from 'axios';
const Attraction_list = () => {
...
const [maindata, setMainData] = useState([]); //setData
const [postsPerPage] = useState(6);
...
let attList = async (areaCode, cityCode) => { //approach openAPI
const url = `...`;
try {
const {data: res} = await axios.get(url)
const list = res.response.body.items.item;
console.log("rendering!")
setMainData(list);
} catch (err) {
console.log(err);
}
}
...
attList(1, 1).then(data => {console.log("then");}) //make maindata
const currentPosts = (tmp) => { //slice data
return tmp.slice(indexOfFirst, indexOfLast);
}
...
return (
<div>
...
<Item rlist={currentPosts(maindata)} moveTo={moveTo} area={area} city={"강남"}></Item>
</div>
);
};
export default Attraction_list;
Function attList brings data from openAPI.
Function currentPosts is executed when component Item is rendering, it returns a sliced list.
I think they executed only once,
Result :
Too much rerendering on this program. Function attList and function currentPost executed too many times. I don't know why.
Why rerendering so much?
You should call the function attList inside a useEffect hook, else it will be called on each rerender of the component.
React.useEffect(()=>{
attList(1, 1)
},[])
When you call
setMainData(list);
inside your attList function, react will rerender your component as there is a state change. This will then run your attList function again which is what is causing the loop.
To prevent this behaviour you can use the useEffect react hook to call the attList function once on the first render and only on the first render.
You have made an infinity loop because the attList will execute setMainData which will then rerender the component again and therefor execute the attList again.
This is why you should use the useEffect hook, to make sure that the attList is only executed when you wan't it to. If you do as shown above, then it will only happen when the component is mounted.