如何在React Firebase应用中切换按钮

时间:2019-01-14 17:31:24

标签: reactjs firebase button

我用Firebase数据库创建了一个React应用程序,该应用程序的概念是“添加到收藏夹”。更准确地说,用户可以在搜索栏中搜索项目,然后通过单击“添加到集合”按钮将每个结果添加到他的集合中。如果需要,用户可以通过单击“删除到收藏夹”按钮从他的收藏夹中删除项目。一切正常!

一切正常,但是如果用户已经在其收藏中,那么我希望“添加到收藏”按钮消失,那就是要显示的“删除”按钮。相反。

有人有想法吗?我尝试在两天内这样做,但没有结果。

这是我的代码:

function addToCollection(hit) {
  const userUid = firebase.auth().currentUser.uid;
  const item = hit
  const ref = hit.objectID 

  firebase.database().ref(`users/${userUid}/collection/${ref}`).update(item);

}

function removeToCollection (hit){
  const userUid = firebase.auth().currentUser.uid;
  const ref = hit.objectID 

  firebase.database().ref(`users/${userUid}/collection/${ref}`).remove();
}


const Hit = ({hit}) =>
    <div className="item">
        <img src={hit.avatarURL} width={150} height={150}></img>
        <h1 className="marque">{hit.marque}</h1>
        <h3 className="numero">{hit.numero}</h3>
        <h4 className="reference">{hit.reference}</h4>
        <h4 className="marquesuite">{hit.marquesuite}</h4>
        <p className="cote">{hit.cote}</p>
        <button className="btn btn-success" onClick={() => addToCollection(hit)}>Add to Collection</button>
        <button className="btn btn-danger" onClick={() => removeToCollection(hit)}>Remove to Collection</button>
    </div>



const Content = () =>
  <div className="text-center">
    <Hits hitComponent={Hit}/>

  </div>






class Catalogue extends React.Component {
  constructor(props){
    super(props);
    this.state = { favorited: this.props.isFavorite };
  }


  render(){

    if(this.state.catalogue === null) {
      return  <p>Le catalogue est vide</p>

    }

      return (
        <div class="container-fluid text-center">
          <h1 className="text-center">Catalogue de capsule</h1>


          <InstantSearch
            apiKey="b91d4104964a4a28c5f99e41484b09ec"
            appId="ZHUPJYFJTW"
            indexName="catalogue">


            <SearchBox translations={{placeholder:'Rechercher une capsule'}}/>



            <Content />  



          </InstantSearch>

        </div> 

      );
  }
}

const authCondition = (authUser) => !!authUser;

export default withAuthorization(authCondition)(Catalogue);

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:-1)

const Hit = ({hit}) =>{
    let itemExists = fasle;
    const itemRef= new Firebase(`users/${userUid}/collection`)
    itemRef.child(hit.objectID).once('value', (snapshot) => {
     itemExists = (snapshot.val() !== null);
     });
    return (<div className="item">
             /*other tags*/
         {itemExists ?
            <button className="btn btn-danger" onClick={() => removeToCollection(hit)}>Remove to Collection</button> : 
            <button className="btn btn-success" onClick={() => addToCollection(hit)}>Add to Collection</button>
          }
    </div>)}