首页 > 解决方案 > 道具仅显示在反应 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);

标签: reactjsredux

解决方案


这仅仅是因为在组件的“第一次加载”时用户数据无效(我假设,我看不到你的减速器)

因此,假设您的减速器将默认用户设置为null

  • 现在这个组件已加载
  • componentDidMount派遣和呼叫getfetchUser
  • getfetchUser需要一些时间...
  • 组件render没有等待,所以它会调用render方法
  • user尚未设置,因为您没有收到服务器的响应
  • 所以在第一次渲染时,你会看到usernull
  • 但是一旦ajax调用返回它就会设置用户并且你很好

所以这就是为什么你会看到这种“奇怪”的行为,但这就是当前实现的方式。

你可以尝试不同的技巧来确保你是好的,比如:

  • 坚持你所做的

  • 添加一个loading标志,这样您就可以知道您正在等待来自服务器的响应。这是更好的选择,因为您可以处理来自服务器的错误。


推荐阅读