gpt4 book ai didi

javascript - React js - setState 和对象数组

转载 作者:行者123 更新时间:2023-12-02 21:55:25 25 4
gpt4 key购买 nike

我是 React 新手,所以我正在努力解决这个问题:

为什么将状态设置为单个对象数组可以工作,但从状态获取数组、推送到它并再次设置为状态却不起作用?

这是工作代码。我有这个 IMAGE 数组处于 as 状态,未初始化:

class PersonalBananas extends React.Component {

constructor(){
super();
this.state = {
username: 0,
images: 0,
pred: 0,
IMAGES: 0
}
this.imgList = this.imgList.bind(this)
}

在 componentDidMount 中我调用 imgList():


componentDidMount() {
let $this = this;

axios.get('http://localhost:8081/auth/username')
.then((response) => {
let uname = response.data;
this.setState({
username: uname
});
})

axios.get('http://localhost:8081/auth/files')
.then((response) => {
let imgs = response.data;
console.log("images response: "+imgs);
this.setState({
images: imgs
},
function() { $this.imgList() }
);
})
}

在 imgList() 内我调用 getImgPred:

imgList = () => {
var $this = this;
const IMAGES = [];
const imgpaths = this.state.images;
console.log("images from imgLis():"+imgpaths);

for (let i = 0; i < imgpaths.length; i++) {
var path = imgpaths[i]
this.getImgPred(path);
console.log("pred:"+$this.state.pred);
}
console.log("IMAGES from imgLis():"+IMAGES);
};


最后我在这里调用 IMAGESpush():


getImgPred = (path) => {
var username = this.state.username;
var $this = this;

let regex = new RegExp(username+'\/(.*?)$');
let imgRegex= /{username}\/(.*?)$/;

let filename = regex.exec(path);
console.log("filename at front:"+filename[1]);
console.log("regex1:"+imgRegex+", regex2:"+regex);

axios.post('http://localhost:8081/auth/imgpred',
"filename=" + filename[1]
).then(function (response) {
console.log("response at front (get img prediction):"+response.data);
if (response.status === 200) {
$this.setState({
pred: response.data
}, function() { $this.IMAGESpush(path) } );
}
});
}

这是问题:当我刚刚初始化 const IMAGES = [] 时,推送到它,然后设置状态 - 它工作正常。我想做的是:const Images = this.state.IMAGES。我做不到。


IMAGESpush = (path) => {
var $this = this;
const IMAGES = [];
IMAGES.push({
src: process.env.PUBLIC_URL +`/${path}`,
thumbnail: process.env.PUBLIC_URL +`/${path}`,
thumbnailWidth: 320,
thumbnailHeight: 320,
caption: $this.state.pred
})
this.setState({
IMAGES: IMAGES
})
}



render() {

return (
<div>
<Gallery images={this.state.IMAGES}/>
</div>
)
}
}

export default PersonalBananas;

最佳答案

推送到数组不会更改其引用,它本质上与 React 的协调算法相同的对象(不会深入比较其状态内部的对象)。

您真正应该做的是创建一个新数组,将旧数组扩展到其中,然后在其上添加一个新元素。像这样:

this.setState({
IMAGES: [...this.state.IMAGES, { /* new object here */ }]
});

您还可以使用 concat 函数来合并数组,因为它不会更改任何数组 - 它会返回一个新数组。

this.setState({
IMAGES: this.state.IMAGES.concat([{ /* new object here */ }])
});

关于javascript - React js - setState 和对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60025570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com