React数组更新后如何触发Modal组件重新渲染
问题核心原因
- 违反React状态更新规则:你在
removeFile函数中直接通过splice修改possibleFiles状态的原数组,React无法检测到直接修改的状态变化,因此不会触发组件重渲染,只有刷新页面才能重置状态看到变化。 - 删除逻辑索引错误:遍历长度和索引用的是入参
files的属性,不是状态里的possibleFiles,就算触发更新也会出现删错文件的问题。 - JSX语法不规范:标签内写的是原生HTML的
class属性,React环境下需要使用className,否则会抛出控制台警告。
修复步骤
- 重写
removeFile方法,永远通过setState传入全新的数组来更新状态,不要直接修改原状态值,用文件唯一id做匹配避免索引错位问题。 - 点击Plot按钮赋值时,对传入的files做浅拷贝,避免直接引用props数组意外修改父组件数据。
- 把所有JSX标签里的
class替换为className。
修复后完整代码
export default function ConfirmBtn({files}){ const [possibleFiles,setPossibleFiles] = useState([]) const removeFile = (fileToRemove) =>{ // 过滤生成新数组传入set方法,触发React重渲染 setPossibleFiles(prevFiles => prevFiles.filter(file => file.id !== fileToRemove.id)) } const mapSelectedFiles = () => { return possibleFiles.map(file => getFiles(file)) } const getFiles = (file) =>{ return( <tr key={file.id} > <td>{file.cal_id + file.e_id}</td> <td><button id={file.f_name} onClick={()=>removeFile(file)}>Remove</button></td> </tr> ) } return( <div className='modealBackgroud'> <button type="button" className="btn btn-primary mt-5 center-block" data-bs-toggle="modal" data-bs-target="#exampleModal" onClick={()=>{ // 浅拷贝props数组,避免直接引用原数组 setPossibleFiles([...files]) }}> Plot </button> <div className="modal fade" id="exampleModal" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLabel">Families Choosen</h5> <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div className="modal-body"> <table className="table table-hover"> <thead> <tr> <th>File</th> </tr> </thead> <tbody> {mapSelectedFiles()} </tbody> </table> </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" className="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> ); }
补充说明:如果后续还需要和父组件的选中文件状态同步,只需要在
removeFile里额外调用父组件传入的更新方法即可,不要直接修改props传入的数组。
内容的提问来源于stack exchange,提问作者boredProjects
相关产品推荐
相关产品推荐

