我正在處理一個簡單的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}
<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,請幫忙!
您的代碼看起來是正確的。我建議在代碼中添加斷點來檢查這些值。 (對於Chrome來說,反應式開發工具插件是完美的) –
也嘗試使用[Redux Devtools for Chrome](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en)以及檢查是否有任何其他行動正在調度,改變你的狀態 – Dane
我只是CONSOL記錄了劇情價值和你的權利它是第一個空,但然後它是一個空對象,我不明白爲什麼 – adesurirey