Ошибка типа: undefined не является объектом (оценивается как _this3props.navigation.state.params) - PullRequest
0 голосов
/ 23 апреля 2020

Я пытаюсь создать приложение для чата с помощью командыact-native expo, и я получаю эту ошибку на странице входящих сообщений. Я также помещаю свою страницу чата (это то, что я пытаюсь перемещать). Пожалуйста, помогите мне! Я поставил экран своей приборной панели и у меня нет маршрута. js file.

"Ошибка типа: undefined не является объектом (оценивается как _this3props.navigation.state.params ')"

        export default class  GelenKutusu extends React.Component {
            state={
                userList:[]
            }
            componentWillMount(){
                firebase.database().ref().child('users').once('value',(snap)=>{
                    let userList=[]
                    snap.forEach((user)=>{
                        const {first_name,profile_picture,uid}=user.val()
                        userList.push({first_name,profile_picture,uid})
                })
                this.setState({userList})
            })
        }
            render() {
              return (
                              <View style={styles.container}>
                        <View style={{alignItems:'center',justifyContent:'center',width:width-40,paddingBottom:10}}>
                            <Text style={{color:'grey',fontWeight:'bold',fontSize:18}}>Inbox</Text>
                        </View>
                        <FlatList
                        data={this.state.userList}
                        keyExtractor={(item,index)=>item.first_name}
                        renderItem={({item})=>
                        <TouchableOpacity onPress={()=> this.props.navigation.navigate('Chat',{user:this.props.navigation.state.params.user, profile:item})} >
                            <View style={{flex:1,backgroundColor:'transparent', flexDirection: 'row', padding:5, width:width}}>
                           <Image style={{height:40, width:40,borderRadius:20}}
                              source={{ uri: item.profile_picture  }} />
                              <View style={{alignItems:'center',justifyContent:'center'}}>
                                 <Text style={{color:'grey', fontWeight:'bold'}}>{item.first_name}</Text>
                              </View>
                              </View>
                              <View style={{width:width, height:1,backgroundColor:'darkgrey'}} />
                              </TouchableOpacity>
                        } />
                    </View>
                );
            }
        } 


Here is chat.js


    export default class chat extends Component{
        state={
            messages:[],
            user:this.props.navigation.state.params.user,
            profile:this.props.navigation.state.params.profile
        }
        componentWillMount(){
            const {user,profile}=this.state
            this.chatID= user.uid > profile.uid? user.uid+'-'+profile.uid:profile.uid+'-'+user.uid
            this.watchChat()
        }
        watchChat=()=>{        firebase.database().ref('messages').child(this.chatID).on('value',snap=>{
                let messages=[]
                snap.forEach(messages=>{
                    messages.push(messages.val())
                })
                messages.reverse()
                this.setState({messages})
            })
        }
        onSend=(messages)=>{
            const {user,profile}=this.state
            relationMessage={}    firebase.database().ref('messages').child(this.chatID).push({...message[0],createdAt:new Date().getTime(),
            })
        }
        render(){
            const {user,profile}=this.state
            const avatar = user.profile_picture
            return(
                <View style={{flex:1}}>
                  <GiftedChat
                    messages={this.state.messages}
                    user={{_id:user.uid,avatar}}
                    onSend={this.onSend()}
                    />
                    </View>
            )
        }
    }




Here is my Dashboard.js screen 


class  DashboardScreen extends Component {

    render(){
        return (

          <NavigationContainer> 

          <Stack.Navigator
         screenOptions={{
           gestureEnabled: true,
           gestureDirection: "horizontal",

           // transitionSpec: {
             // open: config,
             // close: closeConfig
             // }
         }}
         headerMode="float"
         animmation="fade" >
           <Stack.Screen options={{
          headerRight: () => (

            <Ionicons name="ios-search" size={38}  
            style={{ margin: 5, padding: 5}}
            onPress={() => alert('This is a button!')}
            />

          ),
          headerLeft: () => (
            <Ionicons name="ios-add" size={48}  
            style={{ margin: 5, padding: 5}}
            onPress={() => alert('This is a button!')}
            />
          ),
        }} name = "                 "
           component={MyTabs} />
           <Stack.Screen  name="Header" component={MyTabsTop}  />
         </Stack.Navigator>

            </NavigationContainer>

        );
    }
}

export default DashboardScreen;

const Tab = createBottomTabNavigator();
function MyTabs() {
  return (
    <Tab.Navigator
    screenOptions={({ route }) => ({
      tabBarIcon: ({ focused, color, size }) => {
        let iconName;

        if (route.name === 'Home') {
          iconName ='ios-home'
        } 
        else if (route.name === 'Bildirimler') {
          iconName ='ios-notifications'
        }
        else if (route.name === 'GelenKutusu') {
          iconName ='ios-chatboxes'
        }
        else if (route.name === 'Profil') {
          iconName ='ios-contact'
        }

        // You can return any component that you like here!
        return <Ionicons name={iconName} size={size} color={color} />
      }
    })} >
      <Tab.Screen name="Home" component={Home} />
      <Tab.Screen name="Bildirimler" component={Bildirimler} />
      <Tab.Screen name="GelenKutusu" component={GelenKutusu} />
      <Tab.Screen name="Profil" component={Profil} />
    </Tab.Navigator>
  );
}

const Stack = createStackNavigator();
function MyTabsTop() {
    return (
        <Tab.Navigator>
        <Tab.Screen
          name="Home"
          component={Profil}
          options={{ title: 'My home' }}
        />
      </Tab.Navigator>
    );
  }

Это контекст.

1 Ответ

1 голос
/ 23 апреля 2020

Проблема здесь

onPress={()=> this.props.navigation.navigate('Chat',{user:this.props.navigation.state.params.user, profile:item})}

Вы передаете параметр, полученный от другого компонента.

Сначала получите параметры в рендере следующим образом:

 render() {
    /Read the params from the navigation state */
    const { params } = this.props.navigation.state;
    const user= params ? params.user: null;

Здесь вы получите параметр пользователя и будете использовать его в навигации

       onPress={()=> this.props.navigation.navigate('Chat',{user:user, profile:item})}

Надеюсь, это поможет!

...