как исправить ошибку TypeError: невозможно прочитать состояние свойства undefined при использовании реакции native / expo - PullRequest
0 голосов
/ 09 июля 2020

Я в основном пытаюсь обновить состояние, чтобы получить его, когда пользователь выберет свои параметры из двух средств выбора, но я столкнулся с этой ошибкой, когда состояние считается неопределенным. Я не понимаю, почему состояние не определено. Я неправильно указал состояние? Любая помощь очень ценится, спасибо.


import * as React from 'react';
import { StyleSheet, Button, TextInput, Picker } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import FAQ_Screen from './FAQ_Screen';
import NewsScreen from './NewsScreen';
import { createStackNavigator } from '@react-navigation/stack';
import BottomTabNavigator from '../navigation/BottomTabNavigator';
import NotFoundScreen from './NotFoundScreen';


function displayTripResults(state: { startingLocation: string; endingLocation: string; }){

  console.log(state.startingLocation, state.endingLocation)

}

export default function HomeScreen(this: any) {

  const state = {

    startingLocation: 'UNSW',
    endingLocation: 'Central'

  }

  return (
    <View style={styles.container}>
        
        <h1> Search </h1>

        <Text> Starting station </Text>

        <Picker 
          selectedValue = {this.state.startingLocation} 
          onValueChange = {(itemValue, itemIndex) => this.setState({startingLocation: itemValue})}>

          <Picker.Item label="UNSW" value="UNSW" />
          <Picker.Item label="Central" value="Central" />
          <Picker.Item label="Kingsford" value="Kingsford" />
          <Picker.Item label="Eastlakes" value="Eastlakes" />
          
        </Picker>

        <br></br>

        <Text> Ending station </Text>

        <Picker

          selectedValue = {this.state.startingLocation} 
          onValueChange = {(itemValue, itemIndex) => this.setState({endingLocation: itemValue})}>
                                                                                      

          <Picker.Item label="UNSW" value="UNSW" />
          <Picker.Item label="Central" value="Central" />
          <Picker.Item label="Kingsford" value="Kingsford" />
          <Picker.Item label="Eastlakes" value="Eastlakes" />
          
        </Picker>

        <br></br>

        <Button
          onPress={() => displayTripResults(state)}
          title="Search for trips"
          color ="blue"
          accessibilityLabel="A button to allow you to search for light rail trips"
        />
        
    </View>

  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  separator: {
    marginVertical: 30,
    height: 1,
    width: '80%',
  },
});


Ответы [ 2 ]

0 голосов
/ 09 июля 2020

Вы смешали стиль компонента класса со стилем функционального компонента. В функциональном компоненте следует использовать Хуки .

import * as React from 'react';
import { StyleSheet, Button, TextInput, Picker } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import FAQ_Screen from './FAQ_Screen';
import NewsScreen from './NewsScreen';
import { createStackNavigator } from '@react-navigation/stack';
import BottomTabNavigator from '../navigation/BottomTabNavigator';
import NotFoundScreen from './NotFoundScreen';
import {useState} from 'react'

function displayTripResults(state: { startingLocation: string; endingLocation: string; }){

  console.log(state.startingLocation, state.endingLocation)

}

export default function HomeScreen(this: any) {

  const [startingLocation, setStartingLocation] = useState('UNSW');
  const [endingLocation, setEndingLocation] = useState('Central');

  return (
    <View style={styles.container}>
        
        <h1> Search </h1>

        <Text> Starting station </Text>

        <Picker 
          selectedValue = {startingLocation} 
          onValueChange = {(itemValue, itemIndex) => setStartingLocation(itemValue))}>

          <Picker.Item label="UNSW" value="UNSW" />
          <Picker.Item label="Central" value="Central" />
          <Picker.Item label="Kingsford" value="Kingsford" />
          <Picker.Item label="Eastlakes" value="Eastlakes" />
          
        </Picker>

        <br></br>

        <Text> Ending station </Text>

        <Picker

          selectedValue = {startingLocation} 
          onValueChange = {(itemValue, itemIndex) => setEndingLocation( itemValue)}>
                                                                                      

          <Picker.Item label="UNSW" value="UNSW" />
          <Picker.Item label="Central" value="Central" />
          <Picker.Item label="Kingsford" value="Kingsford" />
          <Picker.Item label="Eastlakes" value="Eastlakes" />
          
        </Picker>

        <br></br>

        <Button
          onPress={() => displayTripResults(state)}
          title="Search for trips"
          color ="blue"
          accessibilityLabel="A button to allow you to search for light rail trips"
        />
        
    </View>

  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  separator: {
    marginVertical: 30,
    height: 1,
    width: '80%',
  },
});
0 голосов
/ 09 июля 2020

Попробуйте ... это, и обратитесь к этому для получения дополнительной информации.

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

import BottomTabNavigator from "../navigation/BottomTabNavigator";
import NotFoundScreen from "./NotFoundScreen";

function displayTripResults(state: {
  startingLocation: string,
  endingLocation: string,
}) {
  console.log(state.startingLocation, state.endingLocation);
}

export default function HomeScreen(props: any) {
  const [startingLocation, setStartingLocation] = React.useState("UNSW");
  const [endingLocation, setEndingLocation] = React.useState("Central");
  const displayStuff = { startingLocation, endingLocation };
  return (
    <View style={styles.container}>
      <h1> Search </h1>

      <Text> Starting station </Text>

      <Picker
        selectedValue={startingLocation}
        onValueChange={(itemValue, itemIndex) => setStartingLocation(itemValue)}
      >
        <Picker.Item label="UNSW" value="UNSW" />
        <Picker.Item label="Central" value="Central" />
        <Picker.Item label="Kingsford" value="Kingsford" />
        <Picker.Item label="Eastlakes" value="Eastlakes" />
      </Picker>

      <br></br>

      <Text> Ending station </Text>

      <Picker
        selectedValue={startingLocation}
        onValueChange={(itemValue, itemIndex) => setEndingLocation(itemValue)}
      >
        <Picker.Item label="UNSW" value="UNSW" />
        <Picker.Item label="Central" value="Central" />
        <Picker.Item label="Kingsford" value="Kingsford" />
        <Picker.Item label="Eastlakes" value="Eastlakes" />
      </Picker>

      <br></br>

      <Button
        onPress={() => displayTripResults(displayStuff)}
        title="Search for trips"
        color="blue"
        accessibilityLabel="A button to allow you to search for light rail trips"
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  title: {
    fontSize: 20,
    fontWeight: "bold",
  },
  separator: {
    marginVertical: 30,
    height: 1,
    width: "80%",
  },
});
...