英文:
Undefined error when reading substring in React
问题
I'm getting this error on my React web application: TypeError: Cannot read properties of undefined (reading 'substring').
const DocumentationDetail = () => {
const router = useRouter();
const { user } = useAuth();
const id = router.asPath.substring(1);
const { data } = useDocumentationGet(parseInt(id));
return (
<>
<Head>
<title>{data.title}</title>
</Head>
<main>
<MainLayout>
<div className={styles.container}>
<h1 className={styles.title}>{data.title}</h1>
<span className={styles.info}>Publicado {data.created_at.substring(8, 10)}/{data.created_at.substring(5, 7)}/{data.created_at.substring(0, 4)} por {data.author.name}</span>
<p className={styles.content}>{data.content}</p>
</div>
</MainLayout>
</main>
</>
);
}
export function useDocumentationGet(id) {
const [data, setData] = useState([]);
useEffect(() => {
getDocumentationRequest(id)
.then(res => {
setData(res.data);
})
}, [])
return { data };
}
export async function getDocumentationRequest(id) {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/documentation/${id}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
if (response.ok) {
return { data: await response.json() };
}
return {
status: false,
};
} catch (err) {
return {
status: false,
};
}
}
If I comment the span tag, everything works fine, I don't get it why I only get this undefined error in this line. I also tried using: data ? data.created_at.substring(8,10) : "".... but I got blank spaces on the span line.
英文:
I'm getting this error on my React web application: TypeError: Cannot read properties of undefined (reading 'substring').
const DocumentationDetail = () => {
const router = useRouter();
const { user } = useAuth();
const id = router.asPath.substring(1);
const { data } = useDocumentationGet(parseInt(id));
return (
<>
<Head>
<title>{ data.title }</title>
</Head>
<main>
<MainLayout>
<div className={styles.container}>
<h1 className={styles.title}>{ data.title }</h1>
<span className={styles.info}>Publicado { data.created_at.substring(8, 10) }/{ data.created_at.substring(5, 7) }/{ data.created_at.substring(0, 4) } por { data.author.name }</span>
<p className={styles.content}>{ data.content }</p>
</div>
</MainLayout>
</main>
</>
);
}
export function useDocumentationGet(id) {
const [data, setData] = useState([]);
useEffect(() => {
getDocumentationRequest(id)
.then(res => {
setData(res.data);
})
}, [])
return { data };
}
export async function getDocumentationRequest(id) {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/documentation/${id}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
if (response.ok) {
return { data: await response.json() };
}
return {
status: false,
};
} catch (err) {
return {
status: false,
};
}
}
If I comment the span tag, everything works fine, I don't get it why I only get this undefined error in this line. I also tried using: data ? data.created_at.substring(8,10) : "".... but I got blank spaces on the span line.
答案1
得分: 0
Your data is being fetched after the component is rendered.
> i.e. data.created_at
is empty at the time of render. There are many
> ways to fix this.
One of the way is to use Conditional Rendering using short circuit
, i.e Rendering the component only once Data is ready to be used.
This way the component will render only when data is fetched.
Instead of just rendering the span tag, add a condition as mentioned below.
{
在组件渲染之后获取数据。
> 即 data.created_at
在渲染时为空。有许多
> 修复此问题的方法。
其中一种方法是使用短路条件渲染
,即仅在数据准备好使用时渲染组件。
这样,组件将仅在数据获取时进行渲染。
而不仅仅渲染 span 标签,根据以下条件添加条件。
{
data?.created_at && data?.author?.name &&
<span className={styles.info}>
Publicado { data.created_at.substring(8, 10) }/{ data.created_at.substring(5, 7) }/{ data.created_at.substring(0, 4) } por { data.author.name }
</span>
}
英文:
Your data is being fetched after the component is rendered.
> i.e. data.created_at
is empty at the time of render. There are many
> ways to fix this.
One of the way is to use Conditional Rendering using short circuit
, i.e Rendering the component only once Data is ready to be used.
This way the component will render only when data is fetched.
Instead of just rendering the span tag, add a condition as mentioned below.
{
data?.created_at && data?.author?.name &&
<span className={styles.info}>
Publicado { data.created_at.substring(8, 10) }/{ data.created_at.substring(5, 7) }/{ data.created_at.substring(0, 4) } por { data.author.name }
</span>
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论