Я не могу отправить текст в firebase при нажатии кнопки с редукцией - PullRequest
0 голосов
/ 11 мая 2018

если я напишу это onPress={() => this.submit()} вместо onPress={() => this.onSendBtnPressed()} я могу получить текстовое значение, но если я просто напишу onPress={() => this.onSendBtnPressed()} это, я не смогу увидеть текст в списке сообщений

вот мой чатуй

import React, { Component } from 'react';
import { connect } from 'react-redux';
import {KeyboardAvoidingView, Image, TouchableOpacity, ReactNative, 
StyleSheet }  from 'react-native';
import {Footer, FooterTab} from "native-base";
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll- 
view';
import { View, Title, Screen, ScrollView, TextInput,Text } from 
'@shoutem/ui';
import Messages from '../containers/Messages';
import Input from '../containers/Input';
import { sendMessage } from '../actions';

const mapStateToProps = (state) => ({
chatHeight: state.chatroom.meta.height,
user: state.user,
});

class ChatUI extends Component {
 constructor()
 {
     super();
     this.state = {
        text: '',
        scrollViewHeight: 0,
        inputHeight: 0
    }
 }
 updateValue(text) {
     console.warn(text)

 }      

componentDidMount() {
    this.scrollToBottom(false);
}

componentDidUpdate() {
    this.scrollToBottom();
}

onChangeText(text) { 
    this.setState({text: text})
};

onSendBtnPressed (text) {
    return sendMessage(text, this.props.user)
    this.textInput.clear();
    Keyboard.dismiss();
    }

onScrollViewLayout = (event) => {
    const layout = event.nativeEvent.layout;

    this.setState({
        scrollViewHeight: layout.height
    });
}

onInputLayout = (event) => {
    const layout = event.nativeEvent.layout;

    this.setState({
        inputHeight: layout.height
    });
}

scrollToBottom(animate = false) {
    const { scrollViewHeight, inputHeight } = this.state,
          { chatHeight } = this.props;

    const scrollTo = chatHeight - scrollViewHeight + inputHeight;

 if (scrollTo > 0) {
   this.refs.scroll.scrollToEnd();

}
}
_scrollToInput(reactRef) {
    this.refs.scroll.scrollToFocusedInput(ReactNative.findNodeHandle(reactRef));
}
submit() {
    let collection = {}
    collection.text = this.state.text,
    console.warn(collection);
}

render() {
    return (
   <Screen >   
            <Title style={{paddingTop: 25, paddingLeft: 10, borderBottomWidth: 0.5, backgroundColor: 'white', paddingBottom: 10}}>
            <Image style={{width:80, height: 80}} source={require('../img/11.png')} />
            <Text>                    GENERAL CHAT</Text>
            </Title>
            <KeyboardAwareScrollView ref="scroll"
                                     onLayout={this.onScrollViewLayout}>
                <Messages />
    </KeyboardAwareScrollView>
          <Footer style={{width:360,
                    height:30,
                    backgroundColor:'#fff',
                    borderRadius:20,
                    borderWidth: 0.5,
                    marginBottom: 3,
                    borderColor: 'gray',    
         }}>              
 <TextInput           
                onSubmitEditing = {this.onSubmitEditing}
                multiline
                   onLayout={this.onInputLayout}
                   submitAction={this.onSendBtnPressed}
                   ref="input"
                   placeholder="Say something ..." 
                   onChangeText={(text) => this.onChangeText(text, 'text')}
                   style={{backgroundColor: 'rgba(0,0,0,0)',
                   borderBottomWidth: 1.5, borderColor: '#f8f8f8', fontSize: 16, color: 'gray', paddingBottom:20}}
                   ref={input => { this.textInput = input; } }/>   
          </Footer>
          <TouchableOpacity
                           onPress={() => this.onSendBtnPressed()}
                           style={{marginLeft:280, backgroundColor:'gray', width: 70, height: 30}}
                           title= "send"
           >  
           </TouchableOpacity>

 </Screen>       
    )
}
}

export default connect(mapStateToProps, {sendMessage})(ChatUI);

и вот мои действия

import firebase from '../firebase';
import DeviceInfo from 'react-native-device-info';
import {Actions} from 'react-native-router-flux';
import FCM, { FCMEvent, NotificationType, WillPresentNotificationResult, 
RemoteNotificationResult } from 'react-native-fcm';
import { Platform } from 'react-native';

export const addMessage = (msg) => ({
type: 'ADD_MESSAGE',
 ...msg
});

export const sendMessage = (text, user) => {
return function (dispatch) {
    let msg = {
            text: text,
            time: Date.now(),
            author: {
                name: user.name,
                avatar: user.avatar
            }
        };

    const newMsgRef = firebase.database()
                              .ref('messages')
                              .push();
    msg.id = newMsgRef.key;
    newMsgRef.set(msg);

    dispatch(addMessage(msg));
};
};


export const startFetchingMessages = () => ({
type: 'START_FETCHING_MESSAGES'
});

export const receivedMessages = () => ({
type: 'RECEIVED_MESSAGES',
receivedAt: Date.now()
});

export const fetchMessages = () => {
return function (dispatch) {
    dispatch(startFetchingMessages());

    firebase.database()
            .ref('messages')
            .orderByKey()
            .limitToLast(20)
            .on('value', (snapshot) => {
                setTimeout(() => {
                    const messages = snapshot.val() || [];

                    dispatch(receiveMessages(messages))
                }, 0);
            });
}
}

export const receiveMessages = (messages) => {
return function (dispatch) {
    Object.values(messages).forEach(msg => dispatch(addMessage(msg)));

    dispatch(receivedMessages());
}
}

export const updateMessagesHeight = (event) => {
const layout = event.nativeEvent.layout;

return {
    type: 'UPDATE_MESSAGES_HEIGHT',
    height: layout.height
}
}

export const setUserName = (name) => {
return (dispatch) => {
    dispatch({
        type: 'SET_USER_NAME',
        payload: name

    });
};
};


export const setUserAvatar = (avatar) => ({
type: 'SET_USER_AVATAR',
avatar: avatar && avatar.length > 0 ? avatar : 'avatar.jpg'

});

export const login = () => {
return function (dispatch, getState) {
    dispatch(startAuthorizing());


    firebase.auth()
            .signInAnonymously()
            .then(() => {
               const { name, avatar } = getState().user;

                firebase.database()
                        .ref(`users/`)
                        .push({
                            name,
                            avatar
                        });

                        dispatch(userAuthorized());
                        dispatch(fetchMessages());


            });
}
}

export const checkUserExists = () => {
return function (dispatch) {
    dispatch(startAuthorizing());

    firebase.auth()
            .signInAnonymously()
            .then(() => firebase.database()
                                .ref(`users/${DeviceInfo.getUniqueID()}`)
                                .once('value', (snapshot) => {
                                    const val = snapshot.val();

                                    if (val === null) {
                                        dispatch(userNoExist());
                                    }else{
                                        dispatch(setUserName(val.name));
                                        dispatch(setUserAvatar(val.avatar));
                                        startChatting(dispatch);
                                    }
                                }))
            .catch(err => console.log(err))
}
}

const startChatting = function (dispatch) {
dispatch(userAuthorized());
dispatch(fetchMessages());

FCM.requestPermissions();
FCM.getFCMToken()
   .then(token => {
       console.log(token)
   });
FCM.subscribeToTopic('secret-chatroom');

FCM.on(FCMEvent.Notification, async (notif) => {
    console.log(notif);

    if (Platform.OS === 'ios') {
        switch (notif._notificationType) {
            case NotificationType.Remote:
                notif.finish(RemoteNotificationResult.NewData); //other 
types available: RemoteNotificationResult.NewData, 
RemoteNotificationResult.ResultFailed
                break;
            case NotificationType.NotificationResponse:
                notif.finish();
                break;
            case NotificationType.WillPresent:
                notif.finish(WillPresentNotificationResult.All); //other 
types available: WillPresentNotificationResult.None
                break;
          }
        }
});

FCM.on(FCMEvent.RefreshToken, token => {
    console.log(token);
});
}

export const startAuthorizing = () => ({
type: 'USER_START_AUTHORIZING'
});

export const userAuthorized = () => ({
type: 'USER_AUTHORIZED'
});

export const userNoExist = () => ({
type: 'USER_NO_EXIST'
});

и MessageList

import React, { Component } from 'react';
import {
    ListView, Text, Row, Image,
    View, Subtitle, Caption, Heading
} from '@shoutem/ui';
import moment from 'moment';

const Message = ({ msg }) => (
    <Row>
        <Image styleName="small-avatar top"
            source={{ uri: msg.author.avatar }} />
        <View styleName="vertical">
            <View styleName="horizontal space-between">
                <Subtitle>{msg.author.name}</Subtitle>
                <Caption>{moment(msg.time).from(Date.now())}</Caption>
            </View>
            <Text styleName="multiline">{msg.text}</Text>
        </View>
    </Row>
);

const MessageList = ({ messages, onLayout }) => (
    <ListView data={messages}
            autoHideHeader={true}
            renderRow={msg => <Message msg={msg} />}
            onLayout={onLayout}
            />
);

export default MessageList;

1 Ответ

0 голосов
/ 11 мая 2018
  1. Вы не передаете переменную text в функцию onSendButtonPressed.Похоже, вы должны вызывать его, используя следующий синтаксис:

    onPress={() => this.onSendBtnPressed(someText)}

  2. Ваша onSendBtnPressed() функция имеет оператор return в первой строке, поэтомуКод не будет запущен под оператором возврата (не относится к вашему вопросу, но надеюсь исправить любые другие головные боли ...)

...