持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第16天,点击查看活动详情
前言:
注册完成,现在开始登录,有一说一,今天这个登录+回显个人信息报错缠了我一整天,从早上到晚上,明明逻辑很简单,但是我却总因为打错某个单词而失误!!!真的很难受,不过现在已经舒服了,因为全部解决啦!
正文开始:
注册成功后跳转登陆页面,输入账号和密码点击登录按钮后进入到“/”首页,同时右上角headers显示头像与写文章或者设置等功能。
登录时将email和password进行信息回显且提交至后台接口查找,该功能与注册时一样,此处不再去赘述。
封装request.js请求方法:
user.js
import apiClient from "./apiClient";
export default {
login:(email,password)=>apiClient.post("/users/login",{user:{email,password}}),
}
----------------------------------------------------
index.js集中在一起
export default {
user:userRequset,
}
接下来就使用请求方法:
action.js发送网络请求
const result = await request.user.login(email,password)
dispatch({type:constant.USER_LOGIN_RESULT,result}) //发送登录指令
在reducer中要将登陆后的token与用户信息保存起来,方便后续使用:
reducer中:
case constant.USER_LOGIN_RESULT: //接收到登录指令
const {status,message,data} = action.result
if(status===1){ //登录成功
let token = null
let currentUser = null
//token : 访问用来以后接口
//currentUser : 记录前端登录状态 ,有=》登录,没有 null =>没登录
token = data.token
currentUser = data
//将token 和 currentUser 同步本地 使用localStorage
savaData("currentUser",currentUser)
savaData("token",token)
// 返回state
return {
...state,
email:currentUser.email,
username:currentUser.username,
avatar:currentUser.avatar,
bio:currentUser.bio,
currentUser,
token,
errors:null,
redirect:'/' //注意看这里!!!!!!!!!!!!!
}
}else{ //没有成功,就返回错误信息
return {...state,errors:action.result}
}
上面代码含义为,登陆成功时,status=1,将token和用户信息保存起来之后,同时将redirect进行重定向 -> 首页。
也就是说,当登录页面判断是否发生改变的条件是:redirect是否由“ ”空变为“/”重定向到首页。
如果钩子函数的判断更新为true,则store派发指令跳转到redirect中。
login页面判断是否应该更新
componentDidUpdate(preProps){
if(this.props.redirect && this.props.redirect!==preProps.redirect){
store.dispatch(replace(this.props.redirect))
}
以上完成登陆成功后重定向跳转至首页。
个人信息界面
登陆成功后已经将个人信息拿了回来,并保存在props中,一旦这个变量不为空,也就是接收到了用户信息,那么header就改变ui,为设置/发布文章/头像等标签。
当点击回显后的头像时,将跳转至用户信息页面,并做判断(如果是本人账号,则按钮为编辑信息),如果非本人账号,则按钮为关注/取关。
当点击头像后,link的to为/profile/:username,也就是个人名称,将该username获取到:
this.state={
username:props.match.params.username //获取username
}
在钩子函数中触发get方法获取用户信息:
componentDidMound(){
this.props.getProfle(this.state.username)
}
//增强行为:
getProfile:username=>dispatch(action.getProfile(username)),
然后去action中封装网络请求:
export const getProfile = (username)=>{
return async (dispatch,getState)=>{
try {
//将username传入get方法与后端接口连接
const result = await request.profile.get(username)
dispatch({type:constant.PROFILE_GET_RESULT,result})
} catch (error) { // 错误
dispatch({type:constant.PROFILE_GET_RESULT,result:{status:0,message:error.message,errors:error.errors}})
}
}
}
封装get方法:
profile.js:
get:(username)=>apiClient.get('/follow/'+username),
集中在index.js中:
export default {
user:userRequset,
profile:profileRequset,
}
接下来只需要接收action中指令,写reducer语句更新state就可以了。
case constant.PROFILE_GET_RESULT:
// console.log('reducer result:',action.result)
if(action.result.status===1){ //成功
return {...state,...action.result.data} //展开profile
}else{
return {...state,errors:{message:action.result.message}}
}