reactjs - 在 react/redux 应用程序中存储经过身份验证的用户配置文件的位置
问题描述
我是 Redux 的新手,正在构建一个 React/Redux 应用程序。用户将登录到应用程序,当用户通过身份验证时,我计划返回一个用户配置文件,其中包括 1. 用户姓氏 2. 用户名字 3. 用户电子邮件地址 4. 用户组。
当用户开始从一个页面导航到另一个页面时,我将使用他们所属的用户组隐藏/显示不同组件/页面上的某些部分。
如果需要,我可以在哪里存储应该可以从我的任何组件访问的用户配置文件信息。一些代码的链接将不胜感激。
解决方案
您可以使用 initalState 创建减速器
const initialState = {
firstname: '',
lastname: '',
email: '',
...
}
在我们想要创建从服务器获取数据并将其分派到存储的调度程序函数之后。
export const funnyDispatch = () => async dispatch => {
const response = await fetch('http://example.com/api');
dispatch({
type: 'FUNNY_DATA',
payload: response.userData
})
}
然后声明描述状态如何变化的reducer函数。
function FunnyReducer(state=initalState, action){
switch(action.type){
case 'FUNNY_ACTION':
return {
...state,
firstname: action.payload.firstname, //firstname is property from data which is fetched from server (userData)
lastname: action.payload.lastname,
email: action.payload.email
}
default: return state
}
}
我们得到了我们的数据。
查看redux 文档以获取更多详细信息
编辑
当你需要从 store 中获取数据时,你可以使用 react-redux 的 connect 方法。
您声明名为 mapStateToProps 的变量(您可以选择任何名称),它将状态作为参数(我们不能将其称为存储,因为它不是存储实例,它是状态值)并从初始状态返回所需的属性(在您的减速器中声明)
const mapStateToProps = state => ({
firstname: state.yourReducerName.firstname,
lastname: state.yourReducerName.lastname
})
// yourReducerName is name you give your reducer when you config your store with createStore or combineReducers
那么你要做的就是简单的导出
export default connect(mapStateToProps, {
yourDispatchFunction: (dispatch) => {} //you can export funnyDispatch in this component and put it here
})(YourComponent);
你得到状态属性
this.props.lastname
您可以像这样在事件处理程序(或生命周期方法)中调度函数:
this.props.nameYouGaveToFunnyDispatch()
推荐阅读
- python - 在烧瓶中返回字典时保留顺序
- visual-studio - Visual Studio 调试器不会自动附加到本地 Service Fabric 服务
- sql - 在访问查询中创建连续值组
- python - 有谁知道为什么 ValueErrorException 没有显示?
- python - Django TestCase 302,预计 200
- python - 如何忽略传递给 Python 函数的意外关键字参数
- data-structures - 中序遍历 || 调用堆栈空间要考虑(或)不是?
- excel - 从另一个宏中调用宏会减慢执行速度
- sql - 我需要帮助制作具有多个标准的 where 子句
- prestashop - 问题 API 预习版 1.7