[英]Nothing happens when I click my button in React/Firebase App
我的應用程序上有一個“添加到收藏夾”系統,每個用戶都可以在一個名為“我的收藏”的私人列表中保存項目。 一切工作正常,直到我想按字母順序添加排名。
用戶的每個“收藏夾項目”都按字母順序在頁面上可見,但是當我單擊“刪除按鈕”時,沒有任何反應。 我不太明白問題可能出在哪里。
這是我的代碼(我使用React和Firebase):
import React from 'react';
import AuthUserContext from './AuthUserContext';
import withAuthorization from './withAuthorization';
import * as firebase from 'firebase';
import { config, database, db, auth, itembase, } from '../firebase/firebase';
import Image from 'react-image-resizer';
import _ from 'lodash';
class Collection extends React.Component {
constructor (props) {
super(props)
this.state = {
collection: {}
};
}
//Data from Firebase Database
componentDidMount() {
database.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
});
});
const userUid = firebase.auth().currentUser.uid;
const userRef = firebase.database().ref(`users/${userUid}/collection/items`).orderByChild(`marque`);
userRef.on('value', (snapshot) => {
let newState = [];
snapshot.forEach(function(childSnapshot) {
newState.push({
id: childSnapshot.key,
marque: childSnapshot.val().marque,
marquesuite: childSnapshot.val().marquesuite,
numero: childSnapshot.val().numero,
reference: childSnapshot.val().reference,
cote: childSnapshot.val().cote,
avatar: childSnapshot.val().avatar,
avatarURL: childSnapshot.val().avatarURL,
});
});
this.setState ({
collection: newState
});
});
}
//Remove from user collection
removeToCollection(key, e) {
const userUid = firebase.auth().currentUser.uid;
const item = key;
firebase.database().ref(`users/${userUid}/collection/items/${item}`).remove();
}
renderPosts() {
this.removeToCollection = this.removeToCollection.bind(this);
return _.map(this.state.collection, (collection, key) => {
return (
<div className="item col-md-3" key={key} id={key}>
<img src={this.state.collection[key].avatarURL} height={150} with={150}/>
<h3>{collection.marque}</h3>
<h3>{collection.numero}</h3>
<h4>{collection.marquesuite}</h4>
<h4>{collection.reference}</h4>
<p>{collection.cote}</p>
<div className="text-center">
<button className="btn btn-danger" onClick={(e) => {if(window.confirm('Voulez vous vraiment retirer cette capsule de votre collection ?')){this.removeToCollection(key, e)};}}>Supprimer</button>
</div>
</div>
)
})
}
render(){
if(this.state.collection === null){
return <h2>Votre collection est vide</h2>
}
return (
<div class="container-fluid">
<h1 class="text-center">Votre collection</h1>
{this.renderPosts()}
</div>
)
}
}
const authCondition = (authUser) => !!authUser;
export default withAuthorization(authCondition)(Collection);
預先感謝您的幫助 !
我建議先在構造函數中綁定removeToCollection(),或者先使用箭頭函數,但是對於您的問題,請嘗試在從數據庫中刪除時更新狀態,而不僅僅是在添加到數據庫時進行更新。
編輯:等等,我只是意識到當孩子改變時,.on()函數會被調用,因此它也應該在刪除時也更新狀態,這是我的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.