React-Redux:商店数据没有渲染?

时间:2020-07-06 18:18:12

标签: reactjs redux react-redux

我正在尝试从我的redux商店渲染一个简单的配置文件。实际上,数据已成功提供并映射到我的道具。我可以在控制台中记录配置文件信息。但是当我渲染配置文件数据时,它告诉我该数据未定义。

当我在控制台上登录配置文件时,它会先显示undefined,然后显示数据(参见下图)。我想知道React是否会在数据未定义时尝试呈现。

控制台日志

undefined                        profile.js:28 

Object                           profile.js:28 
bio: "Test"
id: 2
image: "http://localhost:8000/media/default.jpg"

组件

export class ProfileDetail extends Component {

  constructor(props) {
    super(props);  
}

 componentDidMount() {                                                         
    this.props.getProfile(this.props.match.params.id);
  }


    static propTypes = {
      profile: PropTypes.array.isRequired,
      getProfile: PropTypes.func.isRequired,
   };

render() {  
    const profile = this.props.SingleProfile;
    console.log (profile)

    return (

  <Fragment>
        
      <div className="card card-body mt-4 mb-4">
      <h2>{profile.bio}</h2> // if i use here just a string its successfully rendering
      </div>
      </Fragment>
   
    );
  }
}

function mapStateToProps(state, ownProps) {
  const { profile} = state.profile
  const id = parseInt(ownProps.match.params.id, 10)      
  const SingleProfile = profile.find(function(e) {
    return e.id == id;
  });

  return { profile, SingleProfile}
}


export default connect(
  mapStateToProps,
  { getProfile}
)(ProfileDetail);


我有点迷茫,为任何澄清感到高兴。

1 个答案:

答案 0 :(得分:1)

您需要检查是否已加载配置文件。 加载任何数据通常需要一些时间-这不是即时的-这是正常的。 检查配置文件是否存在并显示其属性

<h2>{profile && profile.bio}</h2>

或者,您可以显示一条消息:

<h2>{profile ? profile.bio : "Profile not loaded yet"}</h2>