条件渲染组件会在短期内渲染其他组件,并渲染原始组件

时间:2019-07-29 05:36:40

标签: arrays reactjs

我正在基于循环条件渲染组件。直到条件得到满足,它才不呈现任何结果组件;当条件得到满足时,所需的组件将呈现。但是我只需要满意的组件即可呈现而无需显示no result页面。

{!sourceConfigList.includes(source) ? 
                <Result
                    status="404"
                    title="No Source"
                    subTitle="The Source Does Not Exist"
                    extra={<Link to="/"><Button className="no- 
   source-btn" type="primary">Back Home</Button></Link> }
                />
   : 
    <div className="card-main-flex" >
        <Button type="primary" onClick={this.handleSettings}
             className="source-setting-icon" icon="setting">
         Source Configs
        </Button>
         </div>}

我只想呈现条件满足的组件

2 个答案:

答案 0 :(得分:0)

这是相同的代码,但没有三元运算符。您可以尝试使用此代码。

a = vals.map { |a| a.values_at(*idx) }
  #=> [["k", "r", nil],
  #    ["e", " ", "l"],
  #    ["d", "o", "w"],
  #    ["e", "h", nil]] 
a.transpose
  #=> [["k", "e", "d", "e"],
  #    ["r", " ", "o", "h"],
  #    [nil, "l", "w", nil]] 

答案 1 :(得分:0)

您可以在状态下设置一个布尔值,该状态告诉您是否从api提取了数据,并基于该值呈现了组件。

下面是相同的基本代码示例。

class MyCustomComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      users: [],
      isSourceLoaded: false
    };
  }

  componentDidMount() {
    fetch("https://reqres.in/api/users")
      .then(res => res.json())
      .then((result) => {
      console.log(result)
          this.setState({
            users: result.data,
            isSourceLoaded: true,
          });
        }
      )
  }

  render() {
    if (this.state.isSourceLoaded) {
      if(this.state.users.length) {
        return (
          <div>{JSON.stringify(this.state.users)}</div>
        );
      }
      return (<div>Data not available</div>);
    }

    return (<div>Loading data from source ...</div>);
  }
}

React.render(<MyCustomComponent />, document.getElementById('app'));