React组件条件渲染与if返回,但随后返回主返回

React组件条件渲染与if返回,但随后返回主返回

问题描述:

我正在处理一个简单的React 16 + Redux应用程序,其中PlaysIndex容器呈现两次PlaysList组件,其中plays prop属性值不同。该值有时可能为undefined,因此在这种情况下,我将其设置为null,以便它传递条件返回。如果这是真的,那么条件回报会很快显示出来,但是它会返回到主回报,让我疯狂。React组件条件渲染与if返回,但随后返回主返回

这里是容器呈现组件:

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import _ from 'lodash'; 

import { fetchUserPlays } from '../actions'; 
import PlaysList from '../components/plays_list'; 

class UserPlaysIndex extends Component { 
    componentDidMount() { 
    this.props.fetchUserPlays(); 
    } 

    renderBandsPlays() { 
    return _.map(this.props.plays.bands, band => { 
     return (
     <div key={band.id}> 
      <h3>{band.name}</h3> 
      <PlaysList plays={band.plays} /> 
     </div> 
    ); 
    }) 
    } 

    render() { 
    return (
     <div> 
     <h2>Plays</h2> 
     {this.renderBandsPlays()} 

     <h2>Favorites</h2> 
     <PlaysList plays={this.props.plays.favorites} title="Favorites" /> 
     </div> 
    ); 
    } 
} 

function mapStateToProps(state) { 
    return { plays: state.user_plays }; 
} 

export default connect(mapStateToProps, {fetchUserPlays})(UserPlaysIndex); 

这里是PlaysList组件与条件呈现:

import React from 'react'; 

const PlaysList = props => { 
    // const {plays} = props; 
    let plays; 
    if (props.plays) { 
    plays = props.plays; 
    } else { 
    plays = null; 
    } 

    if (!plays) { 
    // BUG: this is displayed but then it goes back to the main return ! 
    return <div>Nothing to see here.</div>; 
    } 

    const PlayItems = _.map(plays, play => { 
    return (
     <li className="list-group-item" key={play.id}> 
     <div>{play.author}</div> 
     <h4>{play.title}</h4> 
     <div> 
      <i className="fa fa-male"></i> {play.h} &nbsp; 
      <i className="fa fa-female"></i> {play.f} 
     </div> 
     </li> 
    ); 
    }); 

    return (
    <div className="list-group"> 
     {PlayItems} 
    </div> 
); 
}; 

export default PlaysList; 

我知道这又回到了主的回报,因为空值这个仍然没有任何内部呈现<div class="list-group">

Google inspector output screenshot

SOS,请帮忙!

+0

您的代码看起来是正确的。我建议在代码中添加断点来检查这些值。 (对于Chrome来说,反应式开发工具插件是完美的) –

+0

也尝试使用[Redux Devtools for Chrome](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en)以及检查是否有任何其他行动正在调度,改变你的状态 – Dane

+0

我只是CONSOL记录了剧情价值和你的权利它是第一个空,但然后它是一个空对象,我不明白为什么 – adesurirey

我仍然不明白为什么,但我设法去解决这个问题。通过记录plays值,我得到这个:

null 
(9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 
{} 

有问题的道具是第一个空但那么我就得到这个感谢周围lodash改变它变成一个空的对象我如果到:

if (!plays || _.isEmpty(plays)) { 
    return <div>Nothing to see here.</div>; 
} 

我很想知道为什么我的道具在变异,如果有人有答案。

谢谢你对我的帮助。

UPDATE: 这一切都是因为我在我的PlaysReducer默认状态设置为{}所以首先呈现为空,那么它的{},因为没有从componentDidMount()好评!

我所做的改善默认情况下,将其设置为null这样我就可以简化为

if (!plays) { 
    return <div>Nothing to see here.</div>; 
}