[英]Callback doesn't update state
The below function handle uploaded files, for some reason the setFiles
doesn't update the files
list after the callback ends so it causes the previous uploaded file to show up on the page, for example the user uploaded an image 1.jpg
, nothing will show up on the page, next the user uploads a second file- now the first image 1.jpg
will show up, and so on. 下面的函数处理上载的文件,由于某种原因,
setFiles
在回调结束后不会更新files
列表,因此它导致先前上载的文件显示在页面上,例如用户上载了图像1.jpg
,则不会显示在页面上,然后用户上载第二个文件-现在将显示第一个图像1.jpg
,依此类推。
On setFiles
the state is correct and updated but the return
doesn't update the files
state. 在
setFiles
,状态正确且已更新,但return
不会更新files
状态。
Any idea why? 知道为什么吗?
const [files, setFiles] = useState([])
const addFiles = addedFiles => {
const newFiles = Array.from(addedFiles, file => newFileDecorator(file))
setFiles([...files, ...newFiles])
newFiles.forEach(file => {
file.reader.onload = async () => {
const dimensions = await getImageDimensions(file.reader.result)
setFiles(state => {
const index = state.findIndex(f => f.id === file.id)
state[index].readyState = file.reader.readyState
state[index].dimensions = dimensions
return state
})
}
file.reader.readAsDataURL(file.data)
})
}
You are mutating state without creating a new reference for it, so React skips the update as the shallow comparison indicates that they are the same object. 您正在突变状态而未为其创建新引用,因此React跳过更新,因为浅表比较表明它们是同一对象。 Use this pattern instead.
请改用此模式。
setFiles(state => {
const file = state.find(f => f.id === file.id)
file.readyState = file.reader.readyState
file.dimensions = dimensions
return [ ...state, file ]
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.