【问题标题】:How to change value of my react native button component on firebase如何在firebase上更改我的反应本机按钮组件的值
【发布时间】:2022-01-03 04:55:41
【问题描述】:

我正在使用 Flatlist 渲染我的按钮(在从 firebase 获取数据之后)我的 JSON 对象如下

"DEVICES" : {
"6VnNdKZ8" : {
  "switch_1" : {
    "name" : "Air Conditioner",
    "state" : "OFF"
  },
  "switch_2" : {
    "name" : "Fan",
    "state" : "OFF"
  },
  "switch_3" : {
    "name" : "Light",
    "state" : "OFF"
  },
  "switch_4" : {
    "name" : "Power Socket",
    "state" : "OFF"
  }
}

这是渲染按钮的样子

我想通过单击该开关将我们数据库中“状态”的值更新为“开/关”,如何更新确切开关的值

以下代码显示了我如何从 Firebase 获取数据并用于渲染我的开关

注意:“项目”是我的设备的 uid,在这种情况下,您可以忽略该部分(“6VnNdKZ8”),如 JSON 文件中所示

import React,{useEffect,useState} from 'react';
import {View, StyleSheet,Text,FlatList,Dimensions } from 'react-native';
import database from '@react-native-firebase/database';
import EmptyContainer from './EmptyContainer'
import AntDesign from 'react-native-vector-icons/AntDesign';
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;

const Switches = ({items}) => {  
  const [switches, setSwitches] = useState(null)
  
  const getDevice  = async (data) => {
    try {
      database()
        .ref('/DEVICES/'+data)
        .on('value', (snapshot) => {
          if (snapshot.val()) {
            setSwitches(Object.values(snapshot.val()));   
 
          } else {
            console.log("object");
          }
        });
    } catch (error) {
      console.log("error");
    }
  };

  useEffect(() => {
    getDevice(items);
  }, [])


  if(switches != null) {
    return (     
      <FlatList 
      numColumns={2}
      data = {switches}
      keyExtractor={(item) => item.name}
      renderItem={({ item })=>(

       <View style={styles.buttonContainer}>
          <AntDesign style={{marginTop:-20, paddingVertical: 10}} name="bulb1" size={25} color="#666" />
          <Text style={styles.item}>{item.name}</Text>
       </View>
       
      )}
      />   
  );
  }
  return(
    <EmptyContainer/>
  )
    
}

  export default Switches;
  const styles = StyleSheet.create({
    buttonContainer:{
      marginTop:30,
      padding:10,
      height:150,
      borderRadius:22,
      backgroundColor: '#FFFFFF',
      width: windowWidth/2.3,
      marginHorizontal:10,
      justifyContent: 'center',
      color:'#383D41',
      elevation: 4,
      margin:5,

    },
    item:{
      fontFamily:"SegoeUI",
      color: '#383D41',
      fontSize:18,
      fontWeight: 'bold',
    }
  })

【问题讨论】:

    标签: reactjs firebase react-native firebase-realtime-database react-redux


    【解决方案1】:

    useEffect(() => {
        // update firebase func
      }, [switches])

    当更新切换状态时也会更新 Firebase 数据

    https://reactjs.org/docs/hooks-effect.html

    【讨论】:

      【解决方案2】:

      更新 updateValueinFirebase 函数中的值,从而使用 item 属性可以找到当前值。将值从“OFF”更新为“ON”,然后重新获取数据;

      import React,{useEffect,useState} from 'react';
      import {View, StyleSheet,Text,FlatList,Dimensions } from 'react-native';
      import database from '@react-native-firebase/database';
      import EmptyContainer from './EmptyContainer'
      import AntDesign from 'react-native-vector-icons/AntDesign';
      const windowWidth = Dimensions.get('window').width;
      const windowHeight = Dimensions.get('window').height;
      
      const Switches = ({items}) => {  
        const [switches, setSwitches] = useState(null)
        
        const getDevice  = async (data) => {
          try {
            database()
              .ref('/DEVICES/'+data)
              .on('value', (snapshot) => {
                if (snapshot.val()) {
                  setSwitches(Object.values(snapshot.val()));   
       
                } else {
                  console.log("object");
                }
              });
          } catch (error) {
            console.log("error");
          }
        };
      
        useEffect(() => {
          getDevice(items);
        }, [])
      
      
        const updateValueinFirebase = (item)=>{
            // update the value here in item property can find the current value update the value from "OFF" to "ON" then refetch the data;
        }
      
      
        if(switches != null) {
          return (     
            <FlatList 
            numColumns={2}
            data = {switches}
            keyExtractor={(item) => item.name}
            renderItem={({ item })=>(
      
             <View style={styles.buttonContainer} onPress={()=>{updateValueinFirebase(item)}}>
                <AntDesign style={{marginTop:-20, paddingVertical: 10}} name="bulb1" size={25} color="#666" />
                <Text style={styles.item}>{item.name}</Text>
             </View>
             
            )}
            />   
        );
        }
        return(
          <EmptyContainer/>
        )
          
      }
      
        export default Switches;
        const styles = StyleSheet.create({
          buttonContainer:{
            marginTop:30,
            padding:10,
            height:150,
            borderRadius:22,
            backgroundColor: '#FFFFFF',
            width: windowWidth/2.3,
            marginHorizontal:10,
            justifyContent: 'center',
            color:'#383D41',
            elevation: 4,
            margin:5,
      
          },
          item:{
            fontFamily:"SegoeUI",
            color: '#383D41',
            fontSize:18,
            fontWeight: 'bold',
          }
        })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-03
        • 1970-01-01
        • 2018-06-03
        • 2017-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多