首页 > 解决方案 > React 组件在重新加载时崩溃

问题描述

我有一个notes-list组件,它从主组件获取注释数据作为道具。在notes-list组件内部,有一个notes-item组件具有加载的动态路由notesItem-page。因此,对于每一个notes-item都有一个动态 url ,notesItem-page其中包含有关该notesItem对象的所有详细信息。我使用 的Link组件看起来像这样:react-router-domnotes-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;

如果有人可以帮助我,那就太好了,谢谢!

标签: reactjs

解决方案


问题在这里:

<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

推荐阅读