React自定义Hook首次渲染出现NaN路径:useEffect与useState渲染问题
问题原因分析
- 初始状态类型不匹配:你的Hook初始
useState设为数组[],但后续通过setFolderPath设置的是字符串路径,导致组件首次渲染时拿到的是数组,若直接用于路径拼接或数值计算会触发异常。 - 空数组未做边界处理:当
listAll返回的文件夹列表为空时,arrayFolders[arrayFolders.length - 1]会得到undefined,parseInt(undefined)结果为NaN,最终生成错误路径image/event/NaN。 - 依赖数组缺失:
useEffect的依赖数组为空,没有包含postType,当postType参数变化时,Hook不会重新发起请求,可能导致路径不更新。
修复方案
修改你的自定义Hook,优化初始状态、边界处理和依赖逻辑:
import { ref, listAll } from "firebase/storage"; import { FirebaseStorage } from "../firebase/config"; import { useEffect, useState } from "react"; export const useGetLastFolder = (postType) => { // 初始值设为null,保持与后续字符串类型一致,方便组件做加载判断 const [folderPath, setFolderPath] = useState(null); useEffect(() => { // 每次postType变化时重新创建存储引用 const listRef = ref(FirebaseStorage, `image/${postType}`); listAll(listRef) .then((res) => { const arrayFolders = res.prefixes.map(folderRef => folderRef.name); let lastFolder = '0'; // 仅当文件夹列表非空时计算下一个路径 if (arrayFolders.length > 0) { const lastNum = parseInt(arrayFolders.at(-1)); // 校验数值转换结果,避免NaN lastFolder = isNaN(lastNum) ? '0' : (lastNum + 1).toString(); } setFolderPath(`image/${postType}/${lastFolder}`); }) .catch((error) => { console.error('获取文件夹列表失败:', error); // 异常时设置默认路径兜底 setFolderPath(`image/${postType}/0`); }); }, [postType]) // 添加postType到依赖,确保参数变化时重新请求 return { lastPossibleFolderPath: folderPath } }
组件中配合处理加载状态
在FormPage组件中,通过判断lastPossibleFolderPath是否为null,避免展示错误路径:
const { lastPossibleFolderPath } = useGetLastFolder('event'); // 加载状态下显示提示,而非错误路径 if (!lastPossibleFolderPath) { return <div>加载中...</div>; } // 正常渲染逻辑 return ( <div> 待上传图片路径: {lastPossibleFolderPath} {/* 其他表单内容 */} </div> );
内容的提问来源于stack exchange,提问作者man
相关产品推荐
相关产品推荐

