![](/img/trans.png)
[英]my Button in react dosen't work - I use useState and useEffect
[英]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.