簡體   English   中英

更新數組時 useState([]) 不起作用

[英]useState([]) dosen't work when I update an array

我有個問題。 變量interests已填滿,但interestsInput未填滿。 這里到底有什么問題? 我想在文本字段中顯示一個人的興趣,但它沒有顯示數組中的輸入。

const[firstLoad, setFirstLoad] = useState(true);
const [interestsInput, setInterests] = useState([]);

    const selectedTags = (tags) => {
        setTags(tags)
    };

    useEffect(() => {
        if(firstLoad) {
            getInterests();
            
        }
           
        }, [interestsInput]);
 
    const getInterests = () => {
        axios
        .get("http://localhost:4000/interests",
        { }
        )
        .then((res) => {
            if (res.status === 200) {
                var interests = [];
                for (var i = 0; i < firstInterest.length; i++) {
                    //console.log(myStringArray[i]);
                    //console.log(firstInterest[i]['text'])
                    //console.log(firstInterest[i])
                    interests[i] = firstInterest[i]['text'];
                    setInterests([...interestsInput, interests[i]])
                }
                console.log(interests);
                //setInterests([]);
                //setInterests([...interests]);
                console.log(interestsInput)
            }
        })
        .catch((error) => {
            console.log(error);
        });
    }

將新興趣設置在循環之外,而不是在循環內部。

為了簡潔起見,使用.map將對象數組轉換為文本數組。

const getInterests = () => {
    axios
        .get("http://localhost:4000/interests",
            {}
        )
        .then((res) => {
            if (res.status === 200) {
                setInterests([...interestsInput, ...firstInterest.map(int => int.text)]);
            } else {
                throw new Error(res);
            }
        })
        .catch((error) => {
            console.log(error);
        });
};

也像用戶CertainPerformance 建議的那樣,您需要在循環之外設置setState。

// this is redundant, you can achieve this by useEffect with empty array
// const[firstLoad, setFirstLoad] = useState(true);
const [interestsInput, setInterests] = useState([]);

const selectedTags = (tags) => {
  setTags(tags)
};

const getInterests = () => {
  axios
  .get("http://localhost:4000/interests")
  .then((res) => {
    if (res.status === 200) {
      var interests = [];
      for (var i = 0; i < firstInterest.length; i++) {
        interests[i] = firstInterest[i]['text'];
        setInterests([...interestsInput, interests[i]])
      }
    }
  })
  .catch((error) => {
    console.log(error);
  });
}

// Ideally you'd want to put use effects after you have defined your constants & handlers

useEffect(() => {
  // no need of firstLoad condition
  getInterests();
}, []); // this will only run once after first render

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM