reactjs - React 组件在重新加载时崩溃
问题描述
我有一个notes-list
组件,它从主组件获取注释数据作为道具。在notes-list
组件内部,有一个notes-item
组件具有加载的动态路由notesItem-page
。因此,对于每一个notes-item
都有一个动态 url ,notesItem-page
其中包含有关该notesItem
对象的所有详细信息。我使用
的Link
组件看起来像这样:react-router-dom
notes-list
export class NotesList extends Component {
constructor(props) {
super(props);
}
render() {
const { isLoggedIn } = this.props.loggedInContext;
return (
<div className="notes-list">
{this.props.notes.map((notesItem) => (
<Link
to={{
pathname: `${notesItem.slug}`,
id: notesItem._id,
}}
style={{
textDecoration: "none",
color: "#fea82f",
}}
>
<NotesItem notes={notesItem} />
</Link>
))}
</div>
);
}
}
export default loggedInContext(NotesList);
这成功地将我重定向到带有正确道具的 NotesItem 页面,并且在 notesItem 页面中,我收到了作为道具传递的对象的 id,并在 ComponentDidMount() 方法中使用该特定 id 进行 API 调用。这完美地工作。但是,它在重新加载时崩溃。它给出了以下错误:
我猜这是因为 ComponentDidMount 只能工作一次,但我似乎没有找到解决这个问题的替代方案。
notesItem-page 组件如下所示:
export class notesItemPage extends Component {
constructor(props) {
super(props);
this.state = {
notesItem: [],
};
}
componentDidMount() {
fetch(`http://localhost:5000/api/v1/notes/fetch/${this.props.location.id}`)
.then((notesItem) => notesItem.json())
.then((notesItem) =>
this.setState({ notesItem: notesItem.data, isLoaded: true })
);
}
render() {
const { notesItem } = this.state;
return (
<div className="notesItem-details">
<h1> {notesItem.title} Notes</h1>
</div>
);
}
}
export default notesItemPage;
如果有人可以帮助我,那就太好了,谢谢!
解决方案
问题在这里:
<h1> {notesItem.title} Notes</h1>
这里notesItem
来自 axios 调用,并且该数据在第一个组件渲染时不可用,这导致了问题(应用程序崩溃)。
所以改变这个:
<h1> {notesItem.title} Notes</h1>
到
<h1> { notesItem && notesItem.title } Notes</h1> // use it when it is available from axios call
推荐阅读
- reactjs - 基于输入对象的返回类型 Typescript 中的自动完成
- discord - 重新启动 Discord 机器人
- batch-file - 批处理变量在 for 循环中为空
- c# - C# JsonSerializer.Serialize 返回一个空对象
- javascript - 从 Chrome 浏览器发送到服务器的网络摄像头视频 blob 损坏,而从 Mozilla Firefox 发送时工作正常
- mongodb - MongoDB 副本集快照与 Lambda 函数最佳实践
- woocommerce - 更改“下订单”按钮文本以包括订单总计
- javascript - Flutter - 如何在 WebView 中获取 Javascript 回调?
- firefox-addon - 为什么 navigator.credentials.get 函数在 firefox 插件中不起作用
- openwrt - 如何在 OpenWrt 中修改现有的内核包?