如何在React Native中将this.props.key设置为Firebase数据库参考 [英] How to set this.props.key into the Firebase database reference in react native

查看:120
本文介绍了如何在React Native中将this.props.key设置为Firebase数据库参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从另一个组件中检索了值,并显示在TextInput中,以供用户编辑(itemTitle:this.props.title,itemIng:this.props.ing,itemSteps:this.props.steps ) 现在 我尝试在用户按模式按下按钮后将值更新回Firebase.但是我在获取Firebase数据库引用时遇到问题,我可以从另一个组件中获取{this.props._key},但是当我编写为.child(itemKey)时,它不起作用并显示无法查找变量:itemKey有人有类似问题吗?

I have retrieved the values from the other component and displayed in the TextInput for users to edit the values which are the (itemTitle: this.props.title, itemIng: this.props.ing, itemSteps: this.props.steps) and now I'm trying to update the values back to firebase after user pressed the button in modal. But I'm having a problem to get the firebase database reference, I'm able get the {this.props._key} from another component but when I write as a .child(itemKey) it's not working and shows "Can't find variable: itemKey" Does anyone has the similar problem?

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  ScrollView,
  Button,
  TouchableHighlight,
  Modal,
  TextInput,
  ImageBackground
} from 'react-native';
import {Actions}from 'react-native-router-flux';

import firebase from './firebase';

const remote = 'http://l.rgbimg.com/cache1oCOq1/users/b/ba/ba1969/600/mxc1dae.jpg';

export default class RecipeDetails extends React.Component{

  constructor(props){
    super(props);
    this.state={

      modalVisible: false,
      itemTitle: this.props.title,
      itemIng: this.props.ing,
      itemSteps: this.props.steps,
      itemKey: this.props._key.toString(),
    };

    this.vegeRef = this.getRef().child('Vegetarian').child(itemKey);
    this.fastRef = this.getRef().child('Fast Food');
    this.hpRef = this.getRef().child('Healthy');

  }


  setModalVisible(visible){
    this.setState({modalVisible:visible});
  }

  getRef(){
    return firebase.database().ref();
  }

  updateItem(){
    this.setModalVisible(true);
  }

  render(){

    return(
      <View style={styles.container}>
            <Modal
                visible={this.state.modalVisible}
                animationType={'slide'}
                onRequestClose={() => {}}
            >
            <Text>Edit the details and Update.</Text>
                  <TextInput
                    value={this.state.itemTitle}
                    onChangeText ={(itemTitle) => this.setState({ itemTitle })}

                  />
                  <TextInput
                    value={this.state.itemIng}
                    onChangeText ={(itemIng) => this.setState({itemIng})}

                  />
                  <TextInput
                    value={this.state.itemSteps}
                    onChangeText ={(itemSteps) => this.setState({itemSteps})}

                  />

              <View style={styles.modalContainer}>
                <View style={styles.innerContainer}>
                  <Button onPress={() => {
                      this.vegeRef.update({title:this.state.itemTitle, ing:this.state.itemIng, steps:this.state.itemSteps});
                      this.setModalVisible(!this.state.modalVisible)
                    }}
                      title="Save Recipe"
                  >
                  </Button>
                  <Button
                      onPress={() => this.setModalVisible(!this.state.modalVisible)}
                      title="Cancel"
                  >
                  </Button>
                </View>
              </View>
            </Modal>


            <ImageBackground
              style={{
                flex: 1,
                justifyContent: 'center',
                paddingVertical: 35 

              }}
              source={{ uri: remote }}
            >
            <ScrollView style={styles.container2} showsVerticalScrollIndicator={false}>
                <Text style={styles.heading1}>
                  Ingredients
                </Text>
                <Text style={styles.heading2}>
                  {this.props.ing}
                  {this.props._key}
                </Text>

                <Text style={styles.heading1}>
                  Steps
                </Text>
                <Text style={styles.heading2}>
                  {this.props.steps}
                </Text>
            </ScrollView>
            </ImageBackground>

        <View style={styles.action}>
              <TouchableHighlight
                underlayColor='#24ce84'
                onPress={this.updateItem.bind(this)}
              >
                <Text style = {styles.actionText}>Update Recipe</Text>
              </TouchableHighlight>
        </View>
      </View>
    );
  }
}

这是Firebase JSON格式

This is the Firebase JSON format

 "Vegetarian" : {
    "-L3RaWBQchF5rKmVtpNk" : {
      "ing" : "Aasaaaa",
      "steps" : "Aa",
      "title" : "Eeww"
    },
    "-L3WdmePSwkWNN4xB51M" : {
      "ing" : "This is good",
      "steps" : "Nice",
      "title" : "Salad"
    },

推荐答案

您需要将ot itemKey的值更改为this.state.itemKey,并且该值将不在构造函数内部,因为您正在构造函数中初始化状态.同样,无论何时调用任何函数,例如调用update来更新值.尝试在函数内部使用firebase的更新查询,并在Button react元素的onPress事件中使用它.请检查修改后的代码.

You need to change the value ot itemKey to this.state.itemKey and that will not be inside constructor as your are initialising the states in constructor. Also whenever you are calling any function like you have called update to update the values. Try to use the update query of firebase inside a function and use that in onPress event of Button react element. Please check modified code.

import React, { Component } from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    View,
    ScrollView,
    Button,
    TouchableHighlight,
    Modal,
    TextInput,
    ImageBackground
} from 'react-native';
import { Actions } from 'react-native-router-flux';

import firebase from './firebase';

const remote = 'http://l.rgbimg.com/cache1oCOq1/users/b/ba/ba1969/600/mxc1dae.jpg';

export default class RecipeDetails extends React.Component {

    constructor(props) {
        super(props);
        this.state = {

            modalVisible: false,
            itemTitle: this.props.title,
            itemIng: this.props.ing,
            itemSteps: this.props.steps,
            itemKey: this.props._key.toString(),
        };

        // this.vegeRef = this.getRef();
        this.fastRef = this.getRef().child('Fast Food');
        this.hpRef = this.getRef().child('Healthy');

    }

    componentDidMount() {
        this.getRef().child('Vegetarian').on('child_added', s => {
            if (s.exists()) {
                console.log(s.val()) // It will return the new updated object
                console.log(s.key) // It will return the timestamp key
                this.setState({
                    itemTitle: s.val().title,
                    itemIng: s.val().ing,
                    itemSteps: s.val().steps,
                })
            }
        })
    }

    setModalVisible(visible) {
        this.setState({ modalVisible: visible });
    }

    getVegRef = () => {
        this.getRef().child('Vegetarian').child(this.state.itemKey)
    }

    getRef = () => {
        return firebase.database().ref();
    }

    updateVeg = () => {
        this.getVegRef().update(
            {
                title: this.state.itemTitle,
                ing: this.state.itemIng,
                steps: this.state.itemSteps
            });
        this.setModalVisible(!this.state.modalVisible)
    }

    updateItem() {
        this.setModalVisible(true);
    }

    render() {

        return (
            <View style={styles.container}>
                <Modal
                    visible={this.state.modalVisible}
                    animationType={'slide'}
                    onRequestClose={() => { }}
                >
                    <Text>Edit the details and Update.</Text>
                    <TextInput
                        value={this.state.itemTitle}
                        onChangeText={(itemTitle) => this.setState({ itemTitle })}

                    />
                    <TextInput
                        value={this.state.itemIng}
                        onChangeText={(itemIng) => this.setState({ itemIng })}

                    />
                    <TextInput
                        value={this.state.itemSteps}
                        onChangeText={(itemSteps) => this.setState({ itemSteps })}

                    />

                    <View style={styles.modalContainer}>
                        <View style={styles.innerContainer}>
                            <Button onPress={
                                this.updateVeg
                            }
                                title="Save Recipe"
                            >
                            </Button>
                            <Button
                                onPress={() => this.setModalVisible(!this.state.modalVisible)}
                                title="Cancel"
                            >
                            </Button>
                        </View>
                    </View>
                </Modal>


                <ImageBackground
                    style={{
                        flex: 1,
                        justifyContent: 'center',
                        paddingVertical: 35

                    }}
                    source={{ uri: remote }}
                >
                    <ScrollView style={styles.container2} showsVerticalScrollIndicator={false}>
                        <Text style={styles.heading1}>
                            Ingredients
                </Text>
                        <Text style={styles.heading2}>
                            {this.props.ing}
                            {this.props._key}
                        </Text>

                        <Text style={styles.heading1}>
                            Steps
                </Text>
                        <Text style={styles.heading2}>
                            {this.props.steps}
                        </Text>
                    </ScrollView>
                </ImageBackground>

                <View style={styles.action}>
                    <TouchableHighlight
                        underlayColor='#24ce84'
                        onPress={this.updateItem.bind(this)}
                    >
                        <Text style={styles.actionText}>Update Recipe</Text>
                    </TouchableHighlight>
                </View>
            </View>
        );
    }
}

这篇关于如何在React Native中将this.props.key设置为Firebase数据库参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆