reactjs - 道具仅显示在反应 redux 中的内联 if 语句下
问题描述
一直在玩弄一些代码并遇到了一些棘手的问题。目前,如果用户经过身份验证,我将显示用户数据。但是,我必须放 this.props.user 吗?在内联语句中。否则, this.props.user 会以未定义的形式返回,但是 this.props.user 呢?有用。
这是代码
// import React from "react";
// import { connect } from "react-redux";
// import { getUser } from "../store/actions/userActions";
// import { withRouter } from 'react-router-dom';
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom'
import * as actions from '../store/actions/auth'
class UserDetailView extends React.Component {
componentDidMount(){
this.props.onTryAutoSignup()
this.props.getfetchUser(this.props.username)
console.log(this.props)
const user = this.props.user
}
render(){
return(
<div>
{
this.props.user//need this or the below become undefined && this.props.isAuthenticated ?
<div>
Welcome {this.props.user.username} {this.props.user.email}
</div>
:
<div><Link to='/login/'>Login</Link></div>
}
</div>
)
}
}
const mapStateToProps = state => {
return{
isAuthenticated: state.token !== null,
user: state.user,
username: state.username
}
}
const mapStateToDispatch = (dispatch) => ({
logout: () => dispatch(actions.logout()),
onTryAutoSignup: () => dispatch(actions.authCheckState()),
getfetchUser: id => dispatch( actions.fetchUser( id ) )
})
export default connect(mapStateToProps, mapStateToDispatch)(UserDetailView);
解决方案
这仅仅是因为在组件的“第一次加载”时用户数据无效(我假设,我看不到你的减速器)
因此,假设您的减速器将默认用户设置为null
- 现在这个组件已加载
componentDidMount
派遣和呼叫getfetchUser
getfetchUser
需要一些时间...- 组件
render
没有等待,所以它会调用render
方法 - 但
user
尚未设置,因为您没有收到服务器的响应 - 所以在第一次渲染时,你会看到
user
null - 但是一旦ajax调用返回它就会设置用户并且你很好
所以这就是为什么你会看到这种“奇怪”的行为,但这就是当前实现的方式。
你可以尝试不同的技巧来确保你是好的,比如:
坚持你所做的
添加一个
loading
标志,这样您就可以知道您正在等待来自服务器的响应。这是更好的选择,因为您可以处理来自服务器的错误。
推荐阅读
- docker - Docker compose in another directory 影响其他容器
- javascript - jQuery 代码不会在内容脚本中运行,只能在页面上运行
- typescript - 如何检查函数是否存在?
- asp.net - 无法让我的 ajax“添加到购物车部分”功能在 ASP.NET MVC 中工作
- c - 绕 Y 轴旋转 gluLookAt
- python-3.x - 用 Pandas 编写 Excel(不同的工作表和行)
- javascript - 如何使用 useRef 反应钩子关注列表项
- object - 在 Delphi 上,我如何引用仅使用一个变量创建的对象?
- bash - 创建变量列表并稍后调用它们 bash
- spring - Spring Boot Web 应用程序:将 Elastic Beanstalk 与 GitHub 同步