React-native Firebase数据库。Ref.on仅触发一次

时间:2018-09-17 20:46:43

标签: android firebase react-native firebase-realtime-database

我正在使用 Live Reload启用 Android 已连接设备(不是模拟器)上进行开发。每次我保存文件时,它都会在设备上重新加载我的应用-这正是我想要的。

我目前正在使用Firebase进行身份验证和实时数据库。 要检索记录的用户数据,我有一个 Redux操作,它像这样调用firebase.database()

// AppRedux.js
const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'setCurrentUser':
            return { ...state, currentUser: action.value }
            break;
        // { ... }
    }
}

const store = createStore(reducer, applyMiddleware(thunkMiddleware))
export { store }

const setCurrentUser = (user) => {
    return {
        type: "setCurrentUser",
        value: user
    }
}

const watchUserData = () => {
    return function(dispatch) {
        const { currentUser } = firebase.auth()

        if (currentUser) {
            console.log(currentUser.uid) // I always have the right uid, so firebase.auth() always works
            const ref = firebase.database().ref('users/' + currentUser.uid)

            ref.on('value', (snapshot) => {
                const user = snapshot.val()
                console.log(user) // I get there onlye once !

                dispatch(setCurrentUser(user))
            }, (error) => {
                console.log(error)
            })
        }
    }
}
export { setCurrentUser, watchUserData }

这就是我所说的动作:

// Main.js

// { ... other imports}
import { watchUserData } from '../redux/AppRedux'


const mapStateToProps = (state) => {
    return {
        currentUser: state.currentUser
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        watchUserData: () => dispatch(watchUserData())
    }
}

class Main extends React.Component {
    constructor(props) {
        super(props)
    }

    componentWillMount() {
        this.props.watchUserData()
    }

    render() {
        const { currentUser } = this.props

        return (
            <View>
                <Text>Hello { currentUser && currentUser.firstname }!</Text>
            </View>
        )
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Main)

这段代码可以完美运行-但只能执行一次。当Live Reload触发时,它将不再起作用。

请注意,firebase.auth()仍然可以工作,并且给了我uid的权利,但是firebase.database().ref('users/' + currentUser.uid).on('value')不会再被解雇

我必须npm run android(等于react-native run-android)才能再次启动。。直到下一次实时重新加载

请注意,即使我注销并再次登录也无法使用。我仍然需要npm run android才能使其正常工作。

这是我的 package.json ,以防万一

"dependencies": {
    "react": "^16.3.2",
    "react-native": "^0.55.3",
    "react-native-firebase": "^4.3.6",
    "react-native-google-signin": "^1.0.0-rc5",
    "react-navigation": "^2.14.2",
    "react-redux": "^5.0.7",
    "redux": "^4.0.0",
    "redux-thunk": "^2.3.0"
}

我在做错什么吗?是因为我有一个免费 Firebase计划,并且我打了太多电话或什么事?

2 个答案:

答案 0 :(得分:0)

我认为这与多次派遣有关,请尝试:

dispatch(setCurrentUser(user), { allowMore: true })

您可以在here

上阅读更多内容

答案 1 :(得分:0)

对于任何通过搜索登陆此处的人来说,这似乎是bug in react-native-firebase