ComponentWillMount вызывается после перенаправления - PullRequest
0 голосов
/ 02 марта 2019

Поэтому, когда я нахожусь на странице книги и нажимаю кнопку, чтобы удалить ее, она должна перенаправить на мой профиль пользователя и удалить книгу из базы данных.Но происходит то, что ComponentWillMount снова вызывается для Книги, и он не может ее найти.Может быть, у меня нет четкого понимания этих методов жизненного цикла, но я думал, что ComponentWillMount будет вызываться только один раз при первом рендеринге?Также используется Firebase для базы данных.

Вот соответствующий код (где Book == WIP):

WIP.js

componentWillMount() {
    this.WIPRef.on('value', snapshot => {
      let WIP = snapshot.val()
      this.setState({
        title: WIP.title ? WIP.title : "",
        wordCount: WIP.wc ? WIP.wc : "",
        logline: WIP.logline ? WIP.logline : "",
        draft: WIP.draft ? WIP.draft : "",
        language: WIP.language ? WIP.language : "",
        disclaimers: WIP.disclaimers ? WIP.disclaimers : "",
        improvementAreas: WIP.improvementAreas ? WIP.improvementAreas : "",
        blurb: WIP.blurb ? WIP.blurb : "",
        additionalNotes: WIP.additionalNotes ? WIP.additionalNotes : "",
        writer: WIP.writer ? WIP.writer : "",
        genres: WIP.genres ? WIP.genres : [],
        types: WIP.types ? WIP.types : []
      });
      var promises = []
      var writerRef = firebaseDB.database().ref(`/Users/${WIP.writer}`)
      promises.push(writerRef.once('value')); 
      Promise.all(promises).then((snapshots) => {
        snapshots.forEach((snapshot) => {
          var writer = snapshot.val()
          this.setState({
            writerName: writer.displayName ? writer.displayName : ""
          })
        })
      })
    })
}


removeWIP(WIPId) {
    this.setState({ redirect: true })
    const usersWIPRef = firebaseDB.database().ref(`/Users/${this.state.writer}/WIPs/${this.state.wipId}`)
    this.deleteWIPIndexRecord(this.state.wipId)
    usersWIPRef.remove();
    this.WIPRef.remove();
  }

deleteWIPIndexRecord(wipId) {
    const WIPRef = firebaseDB.database().ref(`WIPs/${wipId}`);
    WIPRef.on('value', snapshot => {
    // Get Algolia's objectID from the Firebase object key
    const objectID = snapshot.key;
    // Remove the object from Algolia
    wipsIndex
      .deleteObject(objectID)
      .then(() => {
        console.log('Firebase object deleted from Algolia', objectID);
      })
      .catch(error => {
        console.error('Error when deleting contact from Algolia', error);
        process.exit(1);
      });
    })
  }






render() {
    if (this.state.redirect === true) {
      return <Redirect to= {{pathname: '/user/' + this.state.writer}} />
    }
    return(
        <Button className="black-bordered-button" 
                      onClick={() => this.removeWIP(WIP.id)}
              >
            Remove Item
        </Button>
    )
  }

Но потом, когда я удаляю книгуЯ получаю эту ошибку: Uncaught TypeError: Cannot read property 'title' of null из этой строки в ComponentWillMount title: WIP.title ? WIP.title : ""

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...