切换按钮取决于React Firebase应用程序中的快照值

时间:2019-01-15 21:28:52

标签: reactjs firebase firebase-realtime-database

我在React环境中是一个全新的人,我尝试制作一个“添加到收藏夹” Web应用程序。为此,我将firebase用于我的数据库,并使用Algolia Search搜索栏。

原理如下:admin用户在admin区域中创建项目,其他用户可以在“目录”部分中看到该项目,并使用由algolia服务提供支持的搜索栏搜索特定的项目。

现在,我想实现一个“添加到收藏夹”功能。为此,我创建了两个功能“添加到收藏集”和“删除收藏集”,每个功能都连接到它们自己的按钮上。一切正常。

但是,我希望当用户将一个项目添加到其收藏夹时,“添加到收藏夹”按钮消失,而这是出现的“从收藏夹中删除”按钮。因此,我创建了一个以let变量开头的函数,该变量的值为“ true”或“ false”,并且我的渲染受该变量的值限制。问题是我认为我需要快照用户集合中各项的键,然后根据该键修改let变量。如果该项目已经在用户的收藏夹中,则该变量指示为“ true”,因此出现的是我的“ remove”按钮。相反,如果该项目不在用户的收藏夹中,则该变量表示“ false”,它是显示的“添加到收藏夹”按钮。

我不知道这是否足够明确。

这是我所关注的代码部分:

const Hit = ({hit}) =>{
  let itemExists = true;
  const userUid = firebase.auth().currentUser.uid;
  const itemRef= firebase.database().ref(`users/${userUid}/collection`);

  //Logic for change the value of itemExist 

 if ( itemExists === false ) {
    return (
      <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={() => removeToCollection(hit)}>Remove to collection</button>      
    </div>
    )} else  {
    return (
      <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>      
    </div>
    )
    }
  }

0 个答案:

没有答案