【问题标题】:How can I conditionally render search results with ReactiveBase如何使用 ReactiveBase 有条件地呈现搜索结果
【发布时间】:2019-05-20 07:33:37
【问题描述】:

我试图在ReactiveBase 内有条件地渲染我的结果组件,但每次我尝试使用三元运算符时都会中断渲染。如果我删除三元,结果显示。

我正在使用<ReactiveList> 组件在我的结果组件中显示结果。

我只想在用户实际提交搜索查询时显示结果。那么如何在用户提交查询后才从内部有条件地呈现结果组件

到目前为止,这是我的代码:

import React, { Component } from 'react';
import { Redirect, withRouter } from 'react-router-dom';
import { ReactiveBase, DataSearch } from '@appbaseio/reactivesearch';

import Results from '../../components/appbaseio-search/Results';

class SearchContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      redirect: false,
      loading: false,
    };
  }

  render() {
    const { pathname } = this.props;
    const { value, loading } = this.state;

    const { redirect } = this.state;
    if (redirect ) {
      return (
        <Redirect
          to={{
            pathname: '/search',
            search: `?q="${value}"`,
          }}
        />
      );
    }

    return (
      <ReactiveBase
        ...>
          <DataSearch
            ...
            />
          { pathname === '/results'
            ? <Results />
          : null
          }
        </ReactiveBase>
    );
  }
}

export default withRouter(SearchContainer);

【问题讨论】:

    标签: reactjs conditional-operator conditional-rendering reactivesearch


    【解决方案1】:

    你考虑过使用 React-Router 吗?或者您可以使用状态而不依赖路径。

    例如:

    render() {
      const { results } = this.state;
      if (results || results.length === 0) {
        return (<ReactiveBase>...</ReactiveBase>);
      } else {
        return (<ReactiveBase><Results /></ReactiveBase>);
      }
    }
    

    【讨论】:

    • 我已经在应用程序中使用 React-Route 并且工作正常。我想保持简单,只使用三元运算符,但我将尝试您的示例,看看它是否有效
    • @user3125823 三元运算符并不总是最好的方法;您甚至可能想考虑让 Results 组件传递一个属性并呈现 React.Fragment 并在该组件中而不是在 SearchContainer 中处理逻辑。
    • 你会如何用 React-Router 做到这一点?
    • 我实际上是使用三元组,使用加载作为状态。但是,我仍然只希望在“/results”路线上显示结果?
    • @user3125823 将您的答案发布为社区 wiki,以便我和其他人可以改进答案:D stackoverflow.blog/2011/08/19/the-future-of-community-wiki
    【解决方案2】:

    归根结底就是放置另一个状态,并使用 componentDidMount 更新它

    this.state = {
       ...
       loading: true,
     };
    
    
    componentDidMount() {
     const { location } = this.props;
     this.setState({ loading: false });
    }
    

    然后在 render() 之后

    const { loading } = this.state;
    

    然后是条件

    { loading === false && location.pathname === '/results'
       ? <Route path="/results" component={Results} />
       : null }
    

    您也可以只渲染组件 &lt;Results /&gt; 而不是使用 RR4-&lt;Route /&gt; - 我都试过了 - 它们都可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-02
      • 2011-01-02
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      相关资源
      最近更新 更多