【问题标题】:React Components Combined on Conditional Render在条件渲染上结合 React 组件
【发布时间】:2018-04-21 13:07:53
【问题描述】:

我有两个同一个类的 React 组件,它们有自己的状态存储数据。我基于通过下拉更改传播的父(区域)的道具有条件地渲染组件。在第一次下拉更改时,组件使用第二个组件的 title 属性呈现,但使用第一个组件的数据。在第二个下拉更改中,它按预期工作。

我已经尝试单独测试这些组件,并且它们可以很好地适应区域属性的变化。我还向其中一个组件添加了一个道具和一个条件,以防止在接收道具时重新渲染,但我得到了相同的结果。我可以根据 region 属性隐藏其中一个组件,但我想通过条件渲染来做到这一点。

var content = null;
if(this.props.region === 'WEST'){
    content = (<Component title={'A'} region={this.props.region} dataSource={'someURL'} />);
}else{
    content = (<Component title={'B'} region={this.props.region} dataSource={'someOTHERURL'} />);
}

return (
    {content}
);

编辑更多细节:

组件在 componentDidMount() 和 componentWillReceiveProps() 上都有对后端的 fetch 调用,用于更新组件的状态。组件的每个实例(title={'A'} 和 title={'B'})在无条件渲染时都能正常工作。最初渲染的组件是否有可能在新组件在其位置渲染的同时尝试更新其状态?

fetch('/table?tablename=' + this.props.tableName + '&region=' + 
    nextProps.region + '&chartName=' + this.props.chartName, {
        method: "GET",
        headers: { "Accept": "application/json", "Content-Type": "application/json" }
        }).then(res => res.json())
        .then(data => this.setState({data: data}));
    }

【问题讨论】:

  • 您显示的代码没有问题。如果不查看其余代码,则无法找到您的错误。顺便说一句,你可以缩短它:return (this.props.region === 'WEST') ? &lt;Component title="A" ... /&gt; : &lt;Component title="B" ... /&gt;

标签: javascript reactjs


【解决方案1】:

如果有空间,我会将其放在评论中,因为它不是答案。

您不必要地安装/卸载组件,这增加了生命周期方法的复杂性。我总是返回一个组件,只更改道具。继续获取componentDidMountcomponentWillReceiveProps,但也要考虑缓存响应。

所以可能是这样的;

const data = {
  WEST: {
    title: 'A',
    url: 'someurl'
  },
  EAST: {
    title: 'B',
    url: 'anotherurl'
  },
}
const dataSource = data[this.props.region];

return <Component title={dataSource.title} region={this.props.region} url={dataSource.url} />

【讨论】:

  • 感谢瑞克的建议。不幸的是,我最终得到了相同的结果。我猜我的问题是由于最初渲染的组件尝试获取并更新自己的状态,可能在其父级发生更改之前。我的证据是在接收道具时发出的 GET 调用是使用第一个组件中的 url。理想情况下,我想阻止第一个组件在道具更改时获取和重新渲染,但我在 componentWillReceiveProps() 或 componentWillUpdate() 中没有任何运气
  • componentWillReceiveProps,你在用nextProps.url吗?
  • 天哪,就是这样!我混合使用 this.props 和 nextProps 进行更新。感谢您在 Rick 上坚持我!
【解决方案2】:

如果您使用的是 shouldComponentUpdate 或 PureComponent,这可能会导致您的问题。如果不查看更多代码,很难诊断问题。

在我看来,组件中的 title 属性在第一次更改时没有得到更新,因为 componentWillReceiveProps 没有被触发。

【讨论】:

  • 我没有使用 shouldComponentUpdate 或 PureComponent。通过终端上的 GET 调用,看起来第一个组件的调用在下拉更新后仍在从 componentWillReceiveProps() 运行,尽管它没有被渲染。
猜你喜欢
  • 2021-06-07
  • 2021-05-26
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
相关资源
最近更新 更多