【问题标题】:Return map() from a Firebase React Component?从 Firebase React 组件返回 map()?
【发布时间】:2021-01-15 22:46:47
【问题描述】:

我希望组件 ItemsFromDB 在我的 Firebase 实时数据库 中的“内容”引用下迭代对象的内容。但是如何让这个组件返回我想要的 map() 函数,因为它在快照箭头函数中?

function ItemsFromDB () {
 return (
   let ref = firebase.database().ref('content')
   ref.child(name).on('value', function (snapshot) {
    snapshot.map((childSnapshot) => 
    <h2>{childSnapshot.val().name}</h2>
    )
  })
 )
}

谢谢!

【问题讨论】:

    标签: reactjs firebase loops components arrow-functions


    【解决方案1】:

    类似的东西

    function ItemsFromDB () {
      const [names, setNames] = React.useState(null);
      
      React.useEffect(() => {
        const ref = firebase.database().ref('content').child('name');
        const callback = snapshot => (
          setNames(snapshot.map(child => child.val().name))
        );
        ref.on('value', callback);
        
        return () => {
          ref.off('value', callback);
        };
      }, []);
      
      if (!names) return null;
      
      return (
        <React.Fragment>
          {names.map(name => <h2>{name}</h2>)}
        </React.Fragment>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2018-12-18
      • 2020-02-03
      • 2022-01-19
      • 2021-10-11
      • 2017-06-20
      • 1970-01-01
      相关资源
      最近更新 更多