簡體   English   中英

使用會話變量從反應流星搜索欄中查詢mongo集合

[英]using Session variable to query mongo collection from react meteor search bar

我有一個位於其自身組件中的搜索欄(因此它位於導航欄中),它使用Session.set創建一個變量,我將在另一個組件中用作搜索詞:

updateSearch(e){


Session.set('searchTerm', e.target.value);
  console.log(Session.get('searchTerm'));
}

render(){
  return(
    <div>
      <form>
          <div className="form-group">
              <input type="text" className="form-control" placeholder="Search Tickets"
              // value={this.state.search}
              onChange={this.updateSearch.bind(this)}/>
          </div>
      </form>
    </div>
  )
}
}

這將成功創建一個輸入的搜索詞。 問題是,當我嘗試使用列表組件中的“ searchTerm”變量來列出我的收藏集時。

import { Tickets } from '../../../imports/collections/tickets';
import TicketSearch from './TicketSearch';

export default class TicketList extends React.Component {
  constructor (props) {
      super(props);
      this.state = {
        tickets: [],
        searchTerm: ''
      };
    }

    componentDidMount() {
      this.ticketTracker = Tracker.autorun(() => {
        Meteor.subscribe('tickets');
        let searchTerm = Session.get('searchTerm');
           if (searchTerm) {

                  let tickets = Tickets.find({$in: { talent: searchTerm}}).fetch()
                  this.setState({ tickets });
                }
                 else {

          let tickets = Tickets.find({}).fetch();
          this.setState({ tickets });
         }
      });
    }

    componentWillUnmount() {
      console.log('componentWillUnmount TicketList');
      this.ticketTracker.stop();
    }

    renderTicketList() {
        if (!this.state.tickets.length) {
          return (
            <div>
              <p>No Tickets Found</p>
            </div>
          )
        }

      return this.state.tickets.map((ticket) => {

     return (
             <div>
                    {ticket.talent}
                    {ticket.city}      
              </div>
              )

  render() {
    return(
      <div>
          {this.renderTicketList()}
      </div>
    );
  }
};

故障單列表組件應顯示所有故障單,直到在搜索欄中輸入了某些內容(該部件正在工作)。 使用搜索欄后,理想情況下,searchTerm將過濾與集合的“ talent”或“ city”字段匹配的所有票證。

假設您的代碼中沒有錯別字或邏輯錯誤,我的第一個建議是使用createContainer

而不是tracker.autorun。 將代碼從tracker.autorun移到createContainer函數,並將searchTerm作為prop傳遞給TicketList。 還將setState代碼移動到componentWillReceiveProps方法。 這是基於我對類似問題的個人經驗,另請參見https://github.com/meteor/react-packages/issues/99

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM