gpt4 book ai didi

javascript - 即使在调用 setState 后组件也不会重新渲染

转载 作者:行者123 更新时间:2023-11-29 10:02:31 25 4
gpt4 key购买 nike

我有一个 React 组件,用户可以在其中上传图片,他还显示了上传图片的预览。他可以通过点击图片对应的删除按钮来删除图片。我正在为此使用 react-dropzone。这是代码:

class UploadImage extends React.Component {
constructor(props) {
super(props);
this.onDrop = this.onDrop.bind(this);
this.deleteImage = this.deleteImage.bind(this);
this.state = {
filesToBeSent: [],
filesPreview: [],
printCount: 10,
};
}

onDrop(acceptedFiles, rejectedFiles) {
const filesToBeSent = this.state.filesToBeSent;
if (filesToBeSent.length < this.state.printCount) {
this.setState(prevState => ({
filesToBeSent: prevState.filesToBeSent.concat([{acceptedFiles}])
}));
console.log(filesToBeSent.length);
for (var i in filesToBeSent) {
console.log(filesToBeSent[i]);
this.setState(prevState => ({
filesPreview: prevState.filesPreview.concat([
<div>
<img src={filesToBeSent[i][0]}/>
<Button variant="fab" aria-label="Delete" onClick={(e) => this.deleteImage(e,i)}>
<DeleteIcon/>
</Button>
</div>
])
}));
}
} else {
alert("you have reached the limit of printing at a time")
}
}

deleteImage(e, id) {
console.log(id);
e.preventDefault();
this.setState({filesToBeSent: this.state.filesToBeSent.filter(function(fid) {
return fid !== id
})});
}

render() {
return(
<div>
<Dropzone onDrop={(files) => this.onDrop(files)}>
<div>
Upload your Property Images Here
</div>
</Dropzone>
{this.state.filesToBeSent.length > 0 ? (
<div>
<h2>
Uploading{this.state.filesToBeSent.length} files...
</h2>
</div>
) : null}
<div>
Files to be printed are: {this.state.filesPreview}
</div>
</div>
)
}
}

export default UploadImage;

我的问题是我的组件即使在添加或删除图像后也不会重新呈现。另外,我已经注意不要直接改变状态数组。有人,请帮忙。

最佳答案

这样试试,我用过ES6

Edit 7myoo2x226 .

关于javascript - 即使在调用 setState 后组件也不会重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52565885/

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