[英]using Session variable to query mongo collection from react meteor search bar
I have a search bar that is in its own component (so that it is in the navbar) and it uses Session.set to create a variable I use in another component as the search term: 我有一个位于其自身组件中的搜索栏(因此它位于导航栏中),它使用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>
)
}
}
This successfully creates a search term as it is entered. 这将成功创建一个输入的搜索词。 The problem is that when I try to use the 'searchTerm' variable in the listing component to list my collections.
问题是,当我尝试使用列表组件中的“ 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>
);
}
};
The ticket list component should be showing all tickets until something is entered into the search bar (that part is working). 故障单列表组件应显示所有故障单,直到在搜索栏中输入了某些内容(该部件正在工作)。 After the search bar is used, ideally the searchTerm will filter any tickets that match the 'talent' or 'city' fields of the collection.
使用搜索栏后,理想情况下,searchTerm将过滤与集合的“ talent”或“ city”字段匹配的所有票证。
Assuming there is no typo or logic bug in your code, my first recommendation is to use createContainer 假设您的代码中没有错别字或逻辑错误,我的第一个建议是使用createContainer
instead of tracker.autorun. 而不是tracker.autorun。 Move your code from tracker.autorun to createContainer function and pass searchTerm as a prop to TicketList.
将代码从tracker.autorun移到createContainer函数,并将searchTerm作为prop传递给TicketList。 Also move setState code to componentWillReceiveProps method.
还将setState代码移动到componentWillReceiveProps方法。 This is from my personal experience with similar issue and also see https://github.com/meteor/react-packages/issues/99 .
这是基于我对类似问题的个人经验,另请参见https://github.com/meteor/react-packages/issues/99 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.