因此,当我进入书页时,单击一个按钮将其删除,它应重定向到我的用户个人资料,并从数据库中删除该书。但是会发生什么,再次为Book调用了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 : ""