2017-10-13 87 views
0

我正在處理一個簡單的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

回答

0

我仍然不明白爲什麼,但我設法去解決這個問題。通過記錄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>; 
}