英文:
how to handle error while rendering component
问题
以下是您要翻译的代码部分:
Let's say I have a child component
function MainContent(prop) {
return (
<main>
<p>{prop.message.message.substring(1, 5)}</p>
</main>
);
}
and rendering it in parent like
function App() {
const data = [
{
message: 'first message',
},
{
message: 'second message',
},
{
//message: 'third message', working
wrongkey: 'third message', // not working
};
return (
<div>
<Header />
{data && data.map((item) => <MainContent message={item} />)}
<Footer />
</div>
);
}
Let's say if there is any wrong data and one of the child components inside the loop gets an error, then the whole page errors,
what I want to avoid whole page error just to show a message of that place of child component where the error occurred.
This is just a sample of what I am trying to achieve. I know I can handle the error of a key like below
{prop.message.message?.substring(1, 5)}
But with actual data, we cannot be sure where the error may occur.
[sample code link][1]
I am using TypeScript in my project
Thanks
[1]: https://stackblitz.com/edit/react-parent-child-component-i4tc25?file=src/MainContent.js
英文:
Let's say I have a child component
function MainContent(prop) {
return (
<main>
<p>{prop.message.message.substring(1, 5)}</p>
</main>
);
}
and rendering it in parent like
function App() {
const data = [
{
message: 'first message',
},
{
message: 'second message',
},
{
//message: 'third message', working
wrongkey: 'third message', // not working
},
];
return (
<div>
<Header />
{data && data.map((item) => <MainContent message={item} />)}
<Footer />
</div>
);
}
Let's say if there is any wrong data and one of the child component inside the loop gets error then the whole page errors,
what I want to avoid whole page error just to show a message of that place of child component where the error occurred.
This is just a sample what I am trying to achieve, I know I can handle error of a key like below
{prop.message.message?.substring(1, 5)}
But with actual data, we cannot be sure where error may occur.
I am using Typescript in my project
Thanks
答案1
得分: 1
你可以使用条件运算符,在数据丢失时显示错误:
function MainContent(prop) {
return (
<main>
<p>{
prop.message.message
? prop.message.message?.substring(1, 5)
: "Error text"
}
</p>
</main>
);
}
英文:
You can use conditional operator and show error in case the data is missing:
function MainContent(prop) {
return (
<main>
<p>{
prop.message.message
? prop.message.message?.substring(1, 5)
: "Error text"
}
</p>
</main>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论