【问题标题】:Conditional rendering component renders other component for short period and renders the original component条件渲染组件在短时间内渲染其他组件并渲染原始组件
【发布时间】:2019-07-29 05:36:40
【问题描述】:

我正在根据循环条件渲染组件。直到条件得到满足,它才会呈现任何结果组件,而当条件得到满足时,所需的组件就会呈现。但我只需要渲染满意的组件而不显示无结果页面。

{!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>}

我只想渲染条件满足的组件

【问题讨论】:

    标签: arrays reactjs


    【解决方案1】:

    代码相同,但没有三元运算符。你可以试试这个代码。

    {
    !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> }
                    />
    }
    

    【讨论】:

    • 你能不能也包含其他组件
    • 我不明白。上面的代码帮助您仅在条件满足时进行渲染,这是您在问题中提到的问题。
    【解决方案2】:

    您可以在 state 中创建一个布尔值,告诉您数据是否从 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'));
    

    【讨论】:

      猜你喜欢
      • 2018-02-17
      • 2021-06-07
      • 1970-01-01
      • 2019-08-07
      • 2022-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      相关资源
      最近更新 更多