首页 文章

在条件渲染上组合的React组件

提问于
浏览
0

我有两个相同类的React组件,它有自己的状态存储数据 . 我基于通过下拉更改传播的父(区域)的prop来有条件地渲染组件 . 在第一个下拉列表更改时,组件使用第二个组件的 Headers prop进行渲染,但是第一个组件的数据 . 在第二次下拉更改它按预期工作 .

我已经尝试过单独测试这些组件,并且它们可以在区域改变时正常工作 . 我还为其中一个组件添加了一个prop,并且有条件防止在接收道具时重新渲染,但我得到了相同的结果 . 我可以隐藏其中一个组件,具体取决于区域prop,但我想通过条件渲染来实现 .

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}));
    }

2 回答

  • 0

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

    你're unnecessarily mounting/unmounting components which is adding complexity with regard to the lifecycle methods. I'总是返回一个组件,只需更改道具 . 继续获取 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} />
    
  • 0

    如果您正在使用shouldComponentUpdate或PureComponent,则可能会导致您的问题 . 如果没有看到更多的代码,很难诊断问题 .

    在我看来,组件中的 Headers prop没有在第一次更改时得到更新,因为componentWillReceiveProps没有被触发 .

相关问题