如何在 class 组件中使用分派或如何重构我的 HOC
How to use dispatch in a class component or how to refacter my HOC
我有以下 HOC 组件,它工作正常,但它在发送时给我一个错误。我无法在 class 组件中使用它,但我该如何解决这个问题?
const withAuthentication = <Props extends object>(
Component: React.ComponentType<Props>
) => {
class WithAuthentication extends React.Component<Props & FirebaseInterface> {
render(): React.ReactNode {
const { firebase, ...props } = this.props
const dispatch = useDispatch()
const [authenticated, setAuthenticated] = useState(false)
const { userId, loggedIn } = useSelector(
(state: Record<string, ReduxProvider>) => state.user
)
useEffect(() => {
const listener = firebase.auth.onAuthStateChanged(authUser => {
if (authUser) {
console.log(authUser)
if (!loggedIn) {
firebase.user(userId).once('value', snapshot => {
dispatch(
)
})
}
setAuthenticated(true)
} else {
dispatch(
addUser({
})
)
setAuthenticated(false)
}
})
return (): void => {
listener()
}
}, [setAuthenticated, firebase, dispatch, loggedIn, userId])
}
}
return withFirebase(WithAuthentication)
}
export default withAuthentication
如有任何帮助,我们将不胜感激!
您不能在 class 组件中使用 useDispatch。
你应该使用导入。
import {connect} from 'react-redux'
import {compose} from 'redux'
...
const {dispatch} = this.props
...
return compose(withFirebase, connect(state => ({}), dispatch => ({dispatch})) )(WithAuthentication)
...
...
我有以下 HOC 组件,它工作正常,但它在发送时给我一个错误。我无法在 class 组件中使用它,但我该如何解决这个问题?
const withAuthentication = <Props extends object>(
Component: React.ComponentType<Props>
) => {
class WithAuthentication extends React.Component<Props & FirebaseInterface> {
render(): React.ReactNode {
const { firebase, ...props } = this.props
const dispatch = useDispatch()
const [authenticated, setAuthenticated] = useState(false)
const { userId, loggedIn } = useSelector(
(state: Record<string, ReduxProvider>) => state.user
)
useEffect(() => {
const listener = firebase.auth.onAuthStateChanged(authUser => {
if (authUser) {
console.log(authUser)
if (!loggedIn) {
firebase.user(userId).once('value', snapshot => {
dispatch(
)
})
}
setAuthenticated(true)
} else {
dispatch(
addUser({
})
)
setAuthenticated(false)
}
})
return (): void => {
listener()
}
}, [setAuthenticated, firebase, dispatch, loggedIn, userId])
}
}
return withFirebase(WithAuthentication)
}
export default withAuthentication
如有任何帮助,我们将不胜感激!
您不能在 class 组件中使用 useDispatch。
你应该使用导入。
import {connect} from 'react-redux'
import {compose} from 'redux'
...
const {dispatch} = this.props
...
return compose(withFirebase, connect(state => ({}), dispatch => ({dispatch})) )(WithAuthentication)
...
...