由于 "Order and size of this array must remain constant" 错误,无法更改数组的状态
Cannot change state of Array due to "Order and size of this array must remain constant" Error
每当我上传一组新文件时,React 都会抛出以下错误:
Warning: The final argument passed to useEffect changed size between
renders. The order and size of this array must remain constant.
Previous: [] Incoming: [[object Object]]
这是我使用的代码:
export default function Files({ onChange }) {
// Step #1: initially `files` is an empty Array
const [files, setFiles] = useState([])
useEffect(() => {
// step #3: Notify the parent of the change
// `files` could be empty or not at this pointt
onChange(files)
}, files)
async function onFilesChange() {
let newFiles = await getNewFiles(...arguments)
// Step #2: Now `files` becomes a populated Array of any give size
setFiles(newFiles)
// setState is async so I cannot notify the parent
// of the change right away by calling onChange() below:
// onChange(newFiles)
// I need to rely on useEffect() instead (see step #3)
}
function onFilesRemoved() {
// empty the `files` array and notify parent via `useEffect()`
setFiles([])
}
return (
<>
<input type="file" multiple onChange={onFilesChange}/>
<button onClick={onFilesRemoved}>remove files</button>
</>
)
}
这个错误对我来说没有意义。每次上传或用户选择删除所有文件时,数组的大小必然会有所不同。
useEffect 挂钩的第二个参数必须是 数组 依赖项。
将 files
替换为 [files]
应该可以。
每当我上传一组新文件时,React 都会抛出以下错误:
Warning: The final argument passed to useEffect changed size between renders. The order and size of this array must remain constant. Previous: [] Incoming: [[object Object]]
这是我使用的代码:
export default function Files({ onChange }) {
// Step #1: initially `files` is an empty Array
const [files, setFiles] = useState([])
useEffect(() => {
// step #3: Notify the parent of the change
// `files` could be empty or not at this pointt
onChange(files)
}, files)
async function onFilesChange() {
let newFiles = await getNewFiles(...arguments)
// Step #2: Now `files` becomes a populated Array of any give size
setFiles(newFiles)
// setState is async so I cannot notify the parent
// of the change right away by calling onChange() below:
// onChange(newFiles)
// I need to rely on useEffect() instead (see step #3)
}
function onFilesRemoved() {
// empty the `files` array and notify parent via `useEffect()`
setFiles([])
}
return (
<>
<input type="file" multiple onChange={onFilesChange}/>
<button onClick={onFilesRemoved}>remove files</button>
</>
)
}
这个错误对我来说没有意义。每次上传或用户选择删除所有文件时,数组的大小必然会有所不同。
useEffect 挂钩的第二个参数必须是 数组 依赖项。
将 files
替换为 [files]
应该可以。