【发布时间】:2020-08-07 10:51:22
【问题描述】:
在 react-native、redux、firebase 项目中,我有一个抽屉组件,它在组件挂载时订阅 onSnapshot 侦听器,并且在卸载时,它调用快照引用。这个组件看起来像这样:
import { onAccountChange } from '../actions/Agenda';
import {dispatch} from 'redux';
class DrawerContentComponent extends React.Component {
constructor (props) {
super(props);
}
componentDidMount(){
this.unsubscribeAccount = firebase.firestore().collection('users').doc(this.props.authUser.uid).onSnapshot((doc) => {
dispatch({type: types.LOAD_ACCOUNT, payload: doc.data()})
});
}
componentWillUnmount() {
this.unsubscribeAccount();
}
< ...rest of component... >
EDIT:
const mapStateToProps = ({ account, auth, inbox, agenda }) => {
const { role, profileImg, legalName, username, rating, phoneNumber } = account;
const { conversations } = inbox;
const { authUser } = auth;
const { events } = agenda;
return {
role,
profileImg,
legalName,
username,
rating,
phoneNumber,
authUser,
conversations,
events
};
};
const mapDispatchToProps = { logoutUser, onProfileChange, onAccountChange, getConversations, getAgenda };
export default connect(mapStateToProps, mapDispatchToProps)(DrawerContentComponent);
}
编辑:onAccountChange():
export const onAccountChange = (uid) => {
return (dispatch) => {
firebase.firestore().collection('users').doc(uid).onSnapshot((doc) => {
dispatch({ type: types.LOAD_ACCOUNT, payload: doc.data() });
});
};
};
上述功能是必要的,因为我无法取消订阅该操作,该操作以前放置在外部目录中以进行操作。
问题:我希望能够以某种方式使用已在操作文件 (getAgenda()) 中创建的函数来实现这一点,而不必重写组件中的代码,因为我目前这样做只是为了有能力在卸载时取消订阅侦听器,这是我想使它工作的唯一方法。
理想情况下,id 喜欢做这样的事情:
componentDidMount() {
this.unsubscribeAgenda = this.props.getAgenda();
}
componentWillUnmount() {
this.unsubscribeAgenda();
}
但是上面的结果是:
TypeError: 'dispatch is not a function' 如果我取出 dispatch 导入,错误是 ReferenceError: Cant find variable: dispatch,我显然需要为 onSnapshot 侦听器调度更改
有什么策略可以解决这个问题?
【问题讨论】:
-
你的 getAgenda 动作创建者是什么样的?
-
我没有一个,我从来不需要一个。我在另一个目录中有我的操作,最初只是通过道具在挂载时调用它们。但这并不能帮助我不得不调用对 onSnapshot 侦听器的引用来分离它并防止应用崩溃
-
你能贴出getAgenda的代码是什么吗?
-
@ZacharyHaber 现在检查一下,为了简洁,用
onAccountChange代替,相同的概念,更少的代码
标签: firebase react-native redux react-redux