我正在研究一个简单的React 16 Redux应用程序,其中 PlaysIndex
容器呈现两次 PlaysList
组件,具有不同的 plays
prop值 . 这个值有时可能是 undefined
所以在这种情况下我将它设置为 null
所以它传递一个条件返回 . 当if为true时,条件返回会快速显示,但然后返回到主返回,让我疯了 .
这是渲染组件的容器:
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;
我知道它会回到主返回,因为对于null值,这仍然是一个没有任何内容的 <div class="list-group">
.
Google inspector output screenshot
SOS,请帮忙!
1 回答
我仍然不明白为什么,但我设法绕过这个 . 通过记录
plays
值,我得到了这个:有问题的道具首先是null然后它变成一个空对象所以我只是绕过这个感谢lodash改变我的if:
我很有兴趣知道为什么我的道具会变异,如果有人有答案的话 .
谢谢你的答案帮助了我 .
UPDATE: 这都是因为我将我的
PlaysReducer
默认状态设置为{}
所以首先渲染为空,然后它是{}
因为没有从componentDidMount()
收到任何东西!我所做的改进是默认设置为
null
所以我可以简化为