проблемы с прохождением реквизита через - PullRequest
0 голосов
/ 18 мая 2018

Эй, ребята,

У меня небольшая проблема с моим кодом.честно говоря, я новичок в React-native, и теперь я действительно застрял в этом навигаторе

мой код:

Component5.js:

import React, {Component} from 'react';
import {AppRegistry, Text, View, ListView, StyleSheet, TouchableHighlight, Button} from 'react-native';
import { StackNavigator, SwitchNavigator } from 'react-navigation';

import OtherScreen from './OtherScreen';

export default class Component5 extends Component{
  static navigationOptions = {
  title: 'Welcome to the app!',
};


constructor(){
    super();
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
        userDataSource: ds,
    };
}

componentDidMount(){
    this.fetchUsers();
}

fetchUsers(){
    fetch('https://jsonplaceholder.typicode.com/users')
        .then((response) => response.json())
        .then((response) => {
            this.setState({
                userDataSource: this.state.userDataSource.cloneWithRows(response)
            });
        });
}

onPress(user){
    this.props.navigation.navigate(
      'Details',
      {user: user}
    )};



renderRow(user, sectionId, rowId, highlightRow){
    return(
        <TouchableHighlight onPress={() => {this.onPress(user)}}>
        <View style={styles.row}>
            <Text style={styles.rowText}>{user.name}: {user.email}</Text>
        </View>
        </TouchableHighlight>
    )
}



    render(){
        return(
          <View style={styles.container}>
            <Button title="Show me more of the app" onPress={this._showMoreApp} />
            <Button title="Actually, sign me out :)" onPress={this._signOutAsync} />
            <ListView
                dataSource={this.state.userDataSource}
                renderRow={this.renderRow.bind(this)}
            />
          </View>
        );
    }
    _showMoreApp = () => {
      this.props.navigation.navigate('OtherScreen');
    };

    _signOutAsync =  () => {
      this.props.navigation.navigate('Login');
    };
}

const styles = StyleSheet.create({
    row: {
        flexDirection:'row',
        justifyContent:'center',
        padding:10,
        backgroundColor: '#f4f4f4',
        marginBottom:3
    },
    rowText: {
        flex:1
    }
});

AppRegistry.registerComponent('Component5', () => Component5);

Подробнее.js

import React, {Component} from 'react';
import {AppRegistry, Text, View, Button} from 'react-native';

export default class Details extends Component{
    constructor(user){
        super(user);
        this.state = {
            name: this.props.user.name,
            email: this.props.user.email
        }
    }

      onPress(){
        this.props.navigation.navigate('Home')
      };


    render(){
        return(
        <View>
          <Text>{this.state.name}</Text>
          <Text>{this.state.email}</Text>
            <Button
                onPress={this.onPress.bind(this)}
                title="Go Back"
            />
        </View>
        );
    }
}


AppRegistry.registerComponent('Details', () => Details);

Проблема:

если я цитирую

      name: this.props.user.name ,
      email: this.props.user.email

, тогда все работает нормально.Но страница сведений пуста, кроме кнопки возврата назад

Моя цель состояла в том, чтобы отобразить свойства, такие как имя и E-Mail пользователя selectetd, на странице сведений

Сообщение об ошибке

TypeError: undefined не является объектом (оценивает '_this.props.user.name')

Мое мнение

Я думаю, что проблема в чем-то в процессе проталкивания свойств, носейчас я нахожусь в точке, где я понятия не имею, что я могу сделать сейчас

Спасибо за вашу помощь и время, которое я действительно ценю

1 Ответ

0 голосов
/ 18 мая 2018

пользовательский объект передает значения через навигацию, поэтому вы должны написать

this.props.navigation.state.params.user.name
...