【问题标题】:invariant violation: App(...)Nothing was returned from render. this usually means a return statement is missing. react native不变违规:App(...) 渲染没有返回任何内容。这通常意味着缺少 return 语句。反应原生
【发布时间】:2020-07-11 13:23:09
【问题描述】:

大家好!我只是想征求您的意见,为什么我的代码在标题处显示错误。我已经解决了 2 天,但还没有解决。我希望有人能帮助我。谢谢!这是我的实际代码。我正在使用 cloudinary 来保存图像(效果很好)和 firestore 作为我的数据库。当我在 Firestore 上为数据库应用 Insert 函数时发生错误。

import React, { useState, Component } from 'react'
import {
  StyleSheet,
  View,
  Text,
  Dimensions,
  TouchableOpacity,
  Image,
  TextInput,
  Platform,
  ActivityIndicator, ScrollView, KeyboardAvoidingView, Picker
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import firebase from './firebase';


const App = (props) => {


  const [photo, setPhoto] = useState('https://res.cloudinary.com/{my_Cloud_name}/image/upload/v1585540130/bg_3__1580384977_49.145.192.210_rnmved.jpg');



  const selectPhotoTapped = () => {
    const options = {
      title: 'Select Photo',
      storageOptions: {
        skipBackup: true,
        path: 'images',
      },
    };


    ImagePicker.showImagePicker(options, (response) => {

       console.log('Response = ', response);
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else {
        const source = {
          uri: response.uri,
          type: response.type,
          name: response.fileName,
        }
        cloudinaryUpload(source)
        console.log('Source: ', source);
        console.log('cloudinary upload: ', photo);
        return (photo);
      }
    });
  }
  const cloudinaryUpload = (photo) => {
    const data = new FormData()
    data.append('file', photo)
    data.append('upload_preset', '{my_upload_present}/')
    data.append("cloud_name", "{my_Cloud_name}/")
    fetch("https://api.cloudinary.com/v1_1/{my_Cloud_name}//upload", {
      method: "post",
      body: data
    }).then(res => res.json()).
      then(data => {
        setPhoto(data.secure_url)

      }).catch(err => {
        Alert.alert("An Error Occured While Uploading")
      })
  }

  class AddPost extends Component {
    state = {

      image: '',
      section: '',
      unit: '',
      price: '',
      product: '',
      status: '',
      hasError: false,
      errorText: '',
       isLoading: false,
    }
    onChangeTitle = title => {
      this.setState({ image })
      this.setState({ section })
      this.setState({ unit })
      this.setState({ price })
      this.setState({ product })
      this.setState({ status })
    }


    onSubmit = async () => {
      try {

        const newDocumentData = this.ref.collection('products').doc().id;
        this.setState({
          loading: true,
        });
        const userId = firebase.auth().currentUser.uid;
        this.ref.collection('products').doc(newDocumentData).set({
          store_id: firebase.auth().currentUser.uid,
          pr_name: this.state.product,
          pr_id: newDocumentData,
          pr_price: this.state.price,
          pr_unit: this.state.unit,
          pr_store_name: firebase.auth().currentUser.email, //change into name of store.
          pr_section : this.state.section,
          pr_image: this .state.image,
          prod_status: 'active',
        }).then((docRef) => {
          this.setState({
            image: '',
            section: '',
            unit: '',
            price: '',
            product: '',
            status: '',
            isloading: false,
          });
          Actions.gold();
        })
      } catch (e) {
        console.error(e)
      }
    }

    render() {
      if (this.state.isLoading) {
        return (
          <View style={{flex: 1, paddingTop: 20}}>
            <ActivityIndicator />
          </View>
        );
      }
  return (
    <View>
      <View style={styles.imageContainer}>
      <Text style={{fontSize: 20, textAlign: 'center', marginBottom: 7}}> Add Product </Text>
      <ScrollView 
          keyboardShouldPersistTaps="handled" 
          showsVerticalScrollIndicator={false}>
      <KeyboardAvoidingView enabled >
      <Image source={{ uri: photo }} style={{
                    width: 200,
                    height: 200,
                    borderRadius: 100,
                    alignSelf: 'center',
                  }}/>
 <TextInput
   label="Enter Product"
   placeholder="Enter Product"
   label="Enter Product"

   value={this.state.product}
            onChangeText={product => this.onChangeTitle(product)}

   underlineColorAndroid='transparent'

   style={styles.TextInputStyleClass}

 />

<TextInput

   placeholder="Enter Price"
   keyboardType={'decimal-pad'}

   value={this.state.price}
   onChangeText={price => this.onChangeTitle(price)}
   underlineColorAndroid='transparent'

   style={styles.TextInputStyleClass}
 />



<Picker 

                   style={{height: 50, width: 300}}
                   onValueChange={(TextInputValue, itemIndex) =>
                   this.setState({unit: TextInputValue})}>
                     <Picker.Item label = "Select Unit" />
               <Picker.Item label = "Kilo" value = "Kilo" />
               <Picker.Item label = "Each" value = "Each" />
               <Picker.Item label = "Bottle" value = "Bottle" />
               <Picker.Item label = "Pack" value = "Pack" />
               <Picker.Item label = "Sack" value = "Sack" />




            </Picker>


          <Picker 

                   style={{height: 50, width: 300}}
                   onValueChange={(TextInputValue, itemIndex) =>
                   this.setState({section: TextInputValue})}>
                     <Picker.Item label = "Select Section" />
               <Picker.Item label = "Meat" value = "Meat" />
               <Picker.Item label = "Vegetable" value = "Vegetable" />
               <Picker.Item label = "Fruits" value = "Fruits" />
               <Picker.Item label = "Biscuits" value = "Biscuits" />
               <Picker.Item label = "Condiments" value = "Condiments" />
               <Picker.Item label = "Canned Goods" value = "Canned Goods" />
               <Picker.Item label = "Drinks" value = "Drinks" />

               <Picker.Item label = "Diapers/Napkin" value = "Diapers/Napkin" />
               <Picker.Item label = "Frozen Products" value = "Frozen Products" />
               <Picker.Item label = "Junk Foods" value = "Junk Foods" />
               <Picker.Item label = "Milk" value = "Milk" />
               <Picker.Item label = "Soap/Shampoo" value = "Soap/Shampoo" />
               <Picker.Item label = "Pesonal Items" value = "Pesonal Items" />
               <Picker.Item label = "Pasta/Noodleslete" value = "Pasta/Noodles" />




            </Picker>


<TextInput

   placeholder="Enter Description"
   multiline={true}
   numberOfLines={4}
   label="Enter Product"
   value={this.state.Description}
   onChangeText={Description => this.onChangeTitle(Description)}                
   underlineColorAndroid='transparent'

   style={styles.TextInputStyleClass}
 />


 <TextInput

   placeholder="Enter image"
   value={ photo }
   onChangeText={image => this.onChangeTitle(image)} 
   underlineColorAndroid='transparent'

   style={styles.TextInputStyleClass}
 />
 <TouchableOpacity onPress={selectPhotoTapped} style={styles.uploadButton}>
          <Text style={styles.uploadButtonText}>Upload</Text>
        </TouchableOpacity>

<TouchableOpacity activeOpacity = { .4 } style={styles.uploadButton} >

  <Text style={styles.TextStyle}> INSERT PRODUCT TO SERVER </Text>

</TouchableOpacity>

<TouchableOpacity activeOpacity = { .4 } style={styles.uploadButton}  >

  <Text style={styles.TextStyle}> SHOW ALL INSERTED PRODUCTS RECORDS</Text>

</TouchableOpacity>
<TouchableOpacity activeOpacity = { .4 }  >

  <Text style={styles.TextStyle}>    </Text>

</TouchableOpacity>
</KeyboardAvoidingView>
        </ScrollView>

      </View>

    </View >
  );
};

}

}
export default App;

const styles = StyleSheet.create({
  imageContainer: {

    height: Dimensions.get('window').height
  },
  backgroundImage: {
    flex: 1,
    resizeMode: 'cover',
  },
  uploadContainer: {
    backgroundColor: 'white',
    borderTopLeftRadius: 45,
    borderTopRightRadius: 45,
    position: 'absolute',
    bottom: 0,
    width: Dimensions.get('window').width,
    height: 200,
  },
  uploadContainerTitle: {
    alignSelf: 'center',
    fontSize: 25,
    margin: 20,
    fontFamily: 'Roboto'
  },
  uploadButton: {
    borderRadius: 16,
    alignSelf: 'center',
    shadowColor: "#000",
    shadowOffset: {
      width: 7,
      height: 5,
    },
    shadowOpacity: 1.58,
    shadowRadius: 9,
    elevation: 4,
    margin: 10,
    padding: 10,
    backgroundColor: '#fe5b29',
    width: Dimensions.get('window').width - 60,
    alignItems: 'center'
  },
  uploadButtonText: {
    color: '#f6f5f8',
    fontSize: 20,
    fontFamily: 'Roboto'
  },

  MainContainer :{

    alignItems: 'center',
    flex:1,
    paddingTop: 30,


  },

  MainContainer_For_Show_StudentList_Activity :{

    flex:1,
    paddingTop: (Platform.OS == 'ios') ? 20 : 0,
    marginLeft: 5,
    marginRight: 5

    },

  TextInputStyleClass: {

  textAlign: 'center',
  width: '90%',
  marginBottom: 7,
  height: 40,
  borderWidth: 1,
  borderColor: '#FF5722',
  borderRadius: 5 ,

  },

  TouchableOpacityStyle: {

    paddingTop:10,
    paddingBottom:10,
    borderRadius:5,
    marginBottom:7,
    width: '90%',
    backgroundColor: '#00BCD4'

  },

  TextStyle:{
    color:'#fff',
    textAlign:'center',
  },

  rowViewContainer: {
    fontSize: 20,
    paddingRight: 10,
    paddingTop: 10,
    paddingBottom: 10,
  },
});

【问题讨论】:

    标签: image react-native error-handling google-cloud-firestore cloudinary


    【解决方案1】:
    1. 返回应该包含您的 JSX 代码以返回Something。
    2. 您当前的返回包含 JSX 代码,但它都在您的 AddPost 类下,而您的 App 函数没有任何可返回的内容。
    3. 您正在使用用于功能组件的 useState 和用于组合类组件的 setState。我建议您在项目中一次只使用一种类型的组件,以使您的代码更简单、更好。

    为了完成这项工作,我建议您应该在 App 的 return 下添加您的 AddPost 类。

    例如

    const App = (props) => {
    //somewhere here 
    return(
    //only if this is your initial file
    //else import other file and write followingly
    <AddPost/>
    )
    
    export default App;
    

    【讨论】:

      猜你喜欢
      • 2019-07-04
      • 2018-08-11
      • 2019-08-18
      • 2021-09-10
      • 1970-01-01
      • 2021-06-24
      • 2020-09-06
      相关资源
      最近更新 更多