reactjs - 如何使用此操作功能获取用户信息?
问题描述
我实际上正在开发一个小型反应应用程序,我有一个动作来检查当前用户是否存在于基于 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 is not an object (evalating 'this.props.getUser().currentUser') ”:
console.log("getting current user: ", this.props.getUser().currentUser )
我希望向我显示 displayName 但我得到了那个错误!
解决方案
您实际上正在寻找减速器。操作处理程序并非旨在将数据返回到您的组件。动作思想是将数据存储到reducer。
下面的代码假定您已将 react-redux 与您的应用程序正确连接。
src/actions/userAction.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/userReducer.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/reducers/index.js
import userReducer from "./userReducer";
export default {
user: userReducer
};
src/components/Example.js
import React from 'react';
import connect from "react-redux/es/connect/connect";
import {getUser} from "../actions/userAction";
class Example extends React.Component {
componentDidMount() {
this.props.getUser();
}
render() {
if (!Object.keys(this.props.user.data).length)
return <div>Loading user's data</div>;
return (
<div>
{ JSON.stringify(this.props.user.data) }
</div>
);
}
}
const mapStateToProps = (state) => {
return {
user: state.user
};
};
export default connect(mapStateToProps, {
getUser,
})(Example);
推荐阅读
- css - Wordpress Astra 免费主题标题
- location - infoPlist 属性不适用于 iTunes 连接的 EXPO 项目
- python - 如何将键:值对添加到简单的 JSON 文件
- android - Gradle 6.5 未构建:ANDROID_AAPT_IGNORE 错误
- python - 变量未定义!(Python)
- django - 从静态文件django加载图片
- jquery - 使用 jQuery 显示来自 JSON 的数据
- c++ - 在一个类中包含多个类
- vba - 从 Outlook 联系人公用文件夹中删除或添加特定联系人
- javascript - 为什么我的 Nuxt.js 应用在使用 Netlify 部署后显示空白页面?