我的项目源码地址
redux
1 | npm i redux react-redux redux-thunk -S |
参考之前我的文章
创建store.js
reducers/notifications和reducers/index.js
在根目录index.js中添加Provider组件 store={store}
在views/Notifications/index.js中引入connect,console看一下this.props里有没有dispatch,编写mapState函数,编写connect(mapState),修改form的dataSource
actions=>完善reducers=>完善view界面里的标为已读的功能
在过程中发现下拉菜单的dot属性不能及时更新,发现是因为之前把下拉菜单写成menu数组,如果想实时更新的话需要把他改成函数即可,可以理解为构造了一个组件。
- 完善loading
登录页UI的实现
这里主要采用Card+Form的布局,在设置less的时候遇到transform: translate3d(-50%,-50%,0)
设置后页面显示模糊,原因是计算的结果并非整数的像素点,解决方法参见csdn上的一篇文章。
redux实现登陆页逻辑
在rap2里mock模拟数据,并在requests里新建对应的axios请求
在reducers里新建users:
写initState:id,displayyName,avatar,role,isLoading(如果有token就改为true,但是token本身要存在storage里)
写函数
1
2
3
4
5
6export default(state=initState,action)=>{
switch(action.type){
default:
return state
}
}
整合到reducers/index.js里
修改index.js里以前遗留的问题:需要权限登录才能访问/admin,修改Route里的render,用component={App}代替,具体的权限跳转转到App组件里设置
修改App.js:引入connect
1 | const mapSate=state=>({ |
修改return里的
1 | this.props.isLogin |
添加actions里面的状态:LOGIN、START_LOGIN、LOGIN_SUCCESS、LOGIN_FAILED
新建actions/user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30import actionTypes from './actionTypes'
import {loginRequest} from '../requests'
const startLogin=()=>{
return{
type:actionTypes.START_LOGIN
}
}
const loginSuccess=()=>{
return{
type:actionTypes.LOGIN_SUCCESS
}
}
const loginFailed=()=>{
return{
type:actionTypes.LOGIN_FAILED
}
}
export default login =(userInfo)=>{
return dispatch=>{
dispatch(startLogin())
loginRequest(userInfo)
.then(resp=>{
console.log(resp)
})
}
}只有同步的东西才能定义actionTypes
修改login/index.js界面
- 写mapState函数,使用connect函数联结
- 引入action/user里的login方法
- 修改onFinish函数,在onFinish里引用login函数
修改actions/user.js
loginSuccess要加参数,login函数的完善
做完之后可以去reducers/user里console一下action看是否显示LOGIN_SUCCESS
修改reducers/user
switch语句分别对应三种情况:开始登陆,登陆成功,登陆失败
修改Login/index.js
Redirect,在render时判断isLogin的状态,true则redirect到admin界面,false则仍返回登录界面
细节部分:在input、checkout组件可以设置disabled={this.props.isLoading},在button组件里可以设置loading属性,即在提交时表单会进入短暂loading状态,更为真实
Storage持久化存储
1.在actions/user.js里
- 在login里对获取到的数据进行存储loaclstorage/sessionstorage
- 在loginFailed里清除存储的authToken
2.在reducers/user里,重新定义isLogin的值
1 | const isLogin = Boolean(window.localStorage.setItem('authToken')) || Boolean(window.sessionStorage.setItem('authToken')) |
3.frame组件里
mapstate函数里多返回avatar和displayName
在合适的地方加上
{this.props.avatar}
等等
4.发现上面步骤的头像和名字尚未显示,因为在actions里面只传递了authToken,要加上
1 | window.localStorage.setItem('userInfo',JSON.stringify(userInfo)) |
退出登录
1.actions/user
写logout函数
2.frame
在onDropdownMenuClick函数里加logout
3.reducers
修改loginFailed函数
- 本文作者: Raphael_Li
- 本文链接: https://lifei-2019.github.io/react14/
- 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!