简体   繁体   English

更新数组时 useState([]) 不起作用

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

I have a problem.我有个问题。 The variable interests is filled up but interestsInput not.变量interests已填满,但interestsInput未填满。 What exactly is the problem here?这里到底有什么问题? I want to show the interests of a person in a textfield, but it doesnt show the input in the array.我想在文本字段中显示一个人的兴趣,但它没有显示数组中的输入。

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

Set the new interests outside of the loop, not inside it.将新兴趣设置在循环之外,而不是在循环内部。

To make things concise, use .map to turn the array of objects into an array of texts.为了简洁起见,使用.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);
        });
};

Also like user CertainPerformance suggested, you'll need to setState outisde the loop.也像用户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.

相关问题 我的反应按钮不起作用 - 我使用 useState 和 useEffect - my Button in react dosen't work - I use useState and useEffect 尝试使用 useState 更新数组的内容,但它不起作用 - trying update the content of array with useState, but it doesn't work 当我将它设置为反应时,useState 不会更新 state - useState won't update the state when I set it in react 当我将它与 onClick 中的其他 function 一起使用时,useState 不起作用 - useState doesn't work when I use it with other function in onClick 当我使用IntelliJ想法开发时,Gulp.watch无法正常工作 - Gulp.watch dosen't work when I use intellij idea to develop 修改元素时更新 useState() 数组 REACT - update useState() array when element is modified REACT 删除输入时搜索框不起作用反应 redux - Searchbox dosen't work when the input is erased react redux 如果我不滚动或单击浏览器,组件内部的 React useState() 数组映射不会更新 - React useState() array mapping inside of component doesn't update if I don't scroll or click on browser 为什么我在组件中导入的 js 不起作用? - why the js I import in my component dosen't work? 当子组件的新值减少时,react useState 数组的值不会更新 - Value of react useState array doesn't update when new value from child component is decremented
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM