【发布时间】:2019-05-31 09:36:12
【问题描述】:
我确定我在这里做了一些愚蠢的事情。我正在尝试编写一个组件,该组件根据数据的获取状态呈现三件事之一。
1) 获取错误时的错误消息。 2) 如果数据正在获取,则显示加载消息。 3) 获取数据时的完整子组件。
现在发生的是 fetch 成功,但 Loading 消息不会消失。在下面的代码示例中,您可以看到我添加了一个 console.log 来确定是否应该进行完整渲染。令我困惑的是,这个将最终记录为真,但仍在显示加载消息。
这个确切的模式似乎适用于这个应用程序中的同级组件,所以我对这里缺少什么感到困惑......这是整个组件,它已被匿名化并去除了样式,但结构在其他方面是相同的。
function mapStateToProps(state) {
return {
Data: state.NewDataReducer,
};
}
const mapDispatchToProps = {
fetchNewData: ActionCreators.fetchNewData,
};
const DataError = () => (
<div>
Error fetching new data!
</div>
);
const DataLoading = () => (
<div>
Loading..
</div>
);
class MainContainer extends PureComponent {
static propTypes = {
choice: PropTypes.string,
fetchNewData: PropTypes.func,
Data: ImmutablePropTypes.map.isRequired,
}
state = {
choice: null,
}
componentDidUpdate(nextProps) {
const { choice, fetchNewData, Data } = this.props;
if(!choice) {
return;
}
if(isFetching(Data)) {
return;
}
const newChoiceSelected = choice !== nextProps.choice;
if(newChoiceSelected) {
fetchNewData({choice});
}
}
handleChangeChoice = (choice) => {
this.setState({
choice: { choice }
});
}
render() {
const { choice, Data } = this.props;
const error = hasFetchError(Data);
const loading = !error && !isFetched(Data);
const renderFull = !loading && !error;
console.log(renderFull);
if(!renderFull) {
return (
<div>
Please wait.
</div>
);
}
const { dataBreakdown } = Data.get("dataKey").toJS();
return (
<div>
<ChildComponent
choice={choice}
dataBreakdown={dataBreakdown}
onSetDrillDown={this.handleChangeChoice}
/>
</div>
);
}
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(MainContainer);
【问题讨论】:
标签: reactjs components state jsx rerender