我实际上正在开发一个小型React应用,我有一个操作要根据uid检查当前用户是否存在于Firestore集合“用户”中,然后获取用户的个人资料信息。 它实际上可以执行此操作,但是我无法在个人资料组件中使用它来显示它!
这是动作文件:
import 'firebase/firestore'
import firebase from 'firebase/app'
const getUser =()=>{
return (dispatch)=>{
firebase.auth().onAuthStateChanged(firebaseUser => {
if(firebaseUser){
firebase.firestore().collection("users").doc(firebaseUser.uid).get().then( doc => {
const { displayName } = doc.data()
//it works and it shows me on console the name i want
console.log("display name in action: ",displayName)
const currentUser = {
uid: firebaseUser.uid,
displayName
}
dispatch({
type:'GET_USER',
currentUser,
})
})
}
})
}
}
export default getUser ;
当我尝试将其记录在我的配置文件中时,它显示此错误“ typeError:undefined不是对象(正在评估'this.props.getUser()。currentUser')”:
console.log("getting current user: ", this.props.getUser().currentUser )
我希望向我显示displayName,但出现错误!
答案 0 :(得分:1)
您实际上正在寻找减速器。动作处理程序并非旨在将数据返回到您的组件。行动的想法是将数据存储到减速器。
下面的代码假定您已将react-redux与应用程序正确连接。
src / actions / userAction.js
Setting.Controller
src / reducers / userReducer.js
import 'firebase/firestore'
import firebase from 'firebase/app'
export const getUser = () => {
return (dispatch) => {
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
firebase.firestore().collection("users").doc(firebaseUser.uid).get().then(doc => {
const {displayName} = doc.data();
const currentUser = {
uid: firebaseUser.uid,
displayName
};
dispatch({
type: 'GET_USER',
payload: currentUser
});
})
}
})
}
};
src / reducers / index.js
const INITIAL_STATE = {
data: {},
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'GET_USER':
return {
...state,
data: action.payload
};
default:
return state;
}
};
src / components / Example.js
import userReducer from "./userReducer";
export default {
user: userReducer
};