地图中的react-native函数

时间:2018-01-17 00:30:34

标签: reactjs react-native jsx

我是反应原生的新手,我正在尝试在rails后端构建连接到ruby的应用程序。

我有一个索引视图,我在其中检索午餐列表,我希望当我点击其中一个时,我会去那个演示文稿。所以我创建了一个特定的视图,我在其中重做api调用以检索午餐数据,然后我显示这个。 问题是它首先尝试读取数据然后在该方法处于e: java.lang.IllegalStateException: failed to analyze: android.databinding.tool.util.LoggedErrorException: Found data binding errors. ****/ data binding error ****msg:Cannot find method buttonClicked on ViewDataBinding file:/Users/.../app/src/main/res/layout/layout.xml loc:107:31 - 107:57 ****\ data binding error **** at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57) at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:137) at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:158) at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:61) at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:107) at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51) at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92) at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:386) at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:96) at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:892) at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96) at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137) at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:919) at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:891) at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:385) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346) at sun.rmi.transport.Transport$1.run(Transport.java:200) at sun.rmi.transport.Transport$1.run(Transport.java:197) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.transport.Transport.serviceCall(Transport.java:196) at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: android.databinding.tool.util.LoggedErrorException: Found data binding errors. ****/ data binding error ****msg:Cannot find method buttonClicked on ViewDataBinding file:/Users/.../app/src/main/res/layout/layout.xml loc:107:31 - 107:57 ****\ data binding error **** at android.databinding.tool.processing.Scope.assertNoError(Scope.java:112) at android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.java:91) at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794) at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$200(JavacProcessingEnvironment.java:91) at com.sun.tools.javac.processing.JavacProcessingEnvironment$DiscoveredProcessors$ProcessorStateIterator.runContributingProcs(JavacProcessingEnvironment.java:627) at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1033) at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1198) at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170) at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1068) at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:73) at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:42) at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:205) at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:166) at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82) at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96) at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106) at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:83) at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:376) at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:67) at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:96) at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:367) at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:132) ... 30 more 之后进行api调用,之后进行api调用,因为我在日志中看到它。

INDEX.js

componentWillMount()

Show.js

import React from 'react';
import { View, Text, Image, StyleSheet, ScrollView, TouchableHighlight } from 'react-native'
import { Card, ListItem, Button } from 'react-native-elements'
import { Actions } from 'react-native-router-flux';

export default class IndexLunches extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lunches: []
    };
    this.show = this.show.bind(this)
  }
  fetchLunches() {
    fetch('http://192.168.1.24:3000/api/v1/lunches', {
      method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        }
    })
    .then((response) => {
      if (response.ok) {
        console.log('RESPONSE OK : GET LUNCHES')
        var lunches = JSON.parse(response._bodyText);
        var headers = response.headers
        console.log(lunches)
        console.log(headers)
        this.setState({lunches: lunches})

      } else {
        alert("Erreur pendant la réceptions des lunchs voir les logs")
        console.log(response)
      }

    })
    .catch(function(error) {
      console.log('There has been a problem with your fetch operation: ' + error.message);
      // ADD THIS THROW error
        throw error;
      })
    .done();

  }

  show(id) {
    Actions.show_lunch({lunch_id: id})
  }

  lunchCard() {
    lunches = this.state.lunches
    return lunches.map((lunch, i) => {
      return(
        <TouchableHighlight key={i} onPress={() => this.show(lunch.id)}>
          <View 
            // key={i}
            // Error here because react auto execute onPress on load
            >
            <Image
              style={{flex: 1, height: 150}}
              source={{ uri: lunch.photos[0].url }}
            />
            <Text>Titre du lunch : {lunch.title}</Text>
            <View>
              <Text>id : {lunch.id}</Text>
            </View>
        </View>
        </TouchableHighlight>
      );
    });
  }
  // Its called before render component
  componentWillMount() {
    this.fetchLunches();
  }
  render () {
    return (
      <ScrollView>
        <Text style={styles.title} > Liste des lunchs </Text>
        <View>
          { this.lunchCard() }
        </View>
      </ScrollView>
    )
  }
}

const styles = StyleSheet.create({
  title: {
    color: "#0000FF",
    fontSize: 16,
    marginBottom: 20,
  },
  text: {

  }
})

CONSOLE.LOG

import React from 'react';
import { View, Text, Image, StyleSheet, ScrollView } from 'react-native'
import { Card, ListItem, Button } from 'react-native-elements'

export default class ShowLunch extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lunch: {},
      lunch_id: this.props.navigation.state.params.lunch_id
    };
  }
  fetchLunch() {
    let id = this.state.lunch_id
    fetch(`http://192.168.1.24:3000/api/v1/lunches/${id}`, {
      method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        }
    })
    .then((response) => {
      if (response.ok) {
        console.log(`RESPONSE OK : GET LUNCH, ID: ${id}` )
        var lunch = JSON.parse(response._bodyText);
        var headers = response.headers
        console.log(lunch.lunch)
        console.log(headers)
        this.setState({lunch: lunch.lunch})

      } else {
        alert("Erreur pendant la réceptions du lunch voir les logs")
        console.log(response)
      }

    })
    .catch(function(error) {
      console.log('There has been a problem with your fetch operation: ' + error.message);
      // ADD THIS THROW error
        throw error;
      })
    .done();

  }

  lunchView() {
    lunch = this.state.lunch
    console.log("ENTER IN LUNCH VIEW")
    console.log(lunch)
    return(
        <View key="lunch">
          <Image
            style={{flex: 1, height: 150}}
            source={{ uri: lunch.photos[0].url }}
          />
          <Text>Titre du lunch : {lunch.title}</Text>
          <View>
            <Text>id : {lunch.id}</Text>
          </View>
      </View>
    );
  }
  // Called before render component
  componentWillMount() {
    this.fetchLunch();
  }
  render () {
    return (
      <ScrollView>
        <Text style={styles.title} >Lunch : </Text>
        <View>
          { this.lunchView() }
        </View>
      </ScrollView>
    )
  }
}

const styles = StyleSheet.create({
  title: {
    color: "#0000FF",
    fontSize: 16,
    marginBottom: 20,
  },
  text: {

  }
})

我尝试使用bind(this)或箭头函数做了几件事,但我不明白。

1 个答案:

答案 0 :(得分:2)

这是React中的典型UI问题。您所要做的就是创建一个if语句,检查是否未设置您需要的任何变量。如果是这种情况,那么您需要显示一个显示加载消息或微调器的UI。

render() {
  if (someVariableIsNotSet) {
    // e.g. if (!lunch) // but make sure to set `lunch: null` in initial state

    return <Text>Loading ...</Text>;
  }

  return (
    {/* Your main view for this component */}
  );
}