简体   繁体   English

带有 function 的 setState 创建无限循环

[英]setState with function creates infinite loop

I need to create some data and set it as an initial state.我需要创建一些数据并将其设置为初始 state。

const initialState = [
{
    name: "Joe",
    email: "joe@lorem.com",
    username: "FOOOO",
    website: "www.foosite.com",
    address: {
        city: "New York",
        street: "Times Square",
        suite: "244/78",
        zipcode: "00000",
    },
},
];

Here I just recreate that data multiple times, as I need more of them.在这里,我只是多次重新创建该数据,因为我需要更多数据。

const createSkeletons = useCallback(() => {
    const arr = [];
    let i;
    for (i = 0; i < 20; i++) {
        initialState.forEach((item) => arr.push(item));
    }
    console.log(arr);
    return arr;
}, []);

And here set them as a state while genuine data are fetching.在这里将它们设置为 state,同时获取真实数据。 The created data will be rendered meanwhile.同时渲染创建的数据。

useEffect(() => {
    setIsFetching(true);
    const initial = createSkeletons();
    setDesigners(initial);
    axios.get(`site.com`).then((res) => {
        setIsFetching(false);
        //setDesigners(res.data);
    });
}, [isFetching, createSkeletons]);

However, this creates an infinite loop.但是,这会创建一个无限循环。 What am I doing wrong?我究竟做错了什么?

You don't need to use useEffect to set the initial state, you can do that directly in the useState :您不需要使用useEffect来设置初始 state,您可以直接在useState中进行设置:

const [designers, setDesigners] = useState(createSkeletons());

useEffect(() => {
    setIsFetching(true);
    axios.get(`site.com`).then((res) => {
        setIsFetching(false);
        setDesigners(res.data);
    });
}, []);

useEffect with [isFetching, createSkeletons] is executed each time isFetching changes, the problem is that you modify isFetching in the useEffect, so it will create a loop. useEffect with [isFetching, createSkeletons] 每次isFetching变化都会执行,问题是你在useEffect中修改了isFetching,所以会产生循环。 just removes isFetching from the parameters只是从参数中删除 isFetching

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM