如何将this.props.key设置为反应本机的Firebase数据库引用

时间:2018-01-30 02:56:51

标签: json database firebase react-native firebase-realtime-database

我从其他组件中检索了值,并在TextInput中显示给用户以编辑值(itemTitle:this.props.title,itemIng:this.props.ing,itemSteps:this.props.steps ) 现在 我在用户按下模态按钮后尝试将值更新回firebase。但是我在获取firebase数据库参考时遇到问题,我可以从另一个组件获取{this.props._key},但是当我写为.child(itemKey)它时不工作和显示"找不到变量:itemKey"有没有人有类似的问题?

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格式

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

1 个答案:

答案 0 :(得分:0)

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

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>
        );
    }
}