我对 useEffect 挂钩有疑问。在下面的代码中,第一个效果会触发一个初始化 firebase 的 redux 操作,如果有用户登录,它会将其数据放入 redux 存储中。这会触发组件中的更新,第二个效果尝试重新运行,我得到控制台日志,但也得到“回调不是函数”错误。之后,initFinished 属性设置为 true,所以效果会再次触发,这次我得到的只是错误。
init effect
navigate out effect false empty
render false WOMCMplIduMFRtRM2VssaMgJ2sL2
Uncaught TypeError: callback is not a function
navigate out effect false WOMCMplIduMFRtRM2VssaMgJ2sL2
render true WOMCMplIduMFRtRM2VssaMgJ2sL2
Uncaught TypeError: callback is not a function
我尝试从效果的依赖数组中添加/删除 deps。我总是得到同样的行为。即使效果中的唯一代码是 console.log,行为也保持不变。效果第一次运行,第二次出错。
组件代码
import React, { useEffect, useMemo } from 'react'
import { Text, View } from 'react-native'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Services } from '../../../reduxActions'
const AuthLoading = ({ init, authUserId, initFinished, navigation }) => {
useEffect(() => {
console.log('init effect')
init()
}, [])
useEffect(() => {
console.log('navigate out effect', initFinished, authUserId || 'empty')
if (initFinished) {
if (authUserId) {
navigation.navigate('App')
} else {
navigation.navigate('Auth')
}
}
}, [authUserId, initFinished])
console.log('render', initFinished, authUserId || 'empty')
return (
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}}
>
<Text>{authUserId || 'Loading...'}</Text>
</View>
)
}
export default connect(
({ services }) => {
return {
authUserId:
services.authUser && services.authUser.uid ? services.authUser.uid : '',
initFinished: services.initFinished
}
},
dispatch => {
return {
init: () => {
dispatch(Services.Actions.init())
}
}
}
)(AuthLoading)
依赖项:
"dependencies": {
"@react-native-community/async-storage": "^1.4.0",
"firebase": "^5.11.1",
"prop-types": "^15.7.2",
"rambda": "^2.5.0",
"react": "16.8.6",
"react-native": "^0.59.6",
"react-native-firebase": "^5.3.1",
"react-native-gesture-handler": "^1.2.1",
"react-native-vector-icons": "^6.4.2",
"react-navigation": "^3.9.1",
"react-redux": "^7.0.3",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"styled-components": "^4.2.0"
},