作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 React、Meteor 和 react-meteor-data 组合的现有代码库。
一切都进展得相对顺利,直到我尝试使用 withTracker 实现搜索功能, React Select ,以及 Meteor 的订阅功能。
import { CollectionAPI } from '../arbitrary_meteormongo_collection';
export const WriteableConnectionToCollection = withTracker(props => {
let connection = Meteor.subscribe('COLLECTION_NAME.searchByName', SEARCH_TEXT_HERE);
let isLoading = connection.ready();
return {
...props,
isLoading: isLoading,
collection: CollectionAPI.find().fetch()
}
})(PRESENTATIONAL_COMPONENT);
我在 google 上搜索了一下,发现将数据获取到 Meteor.subscribe 的常见解决方案是使用 URL 参数之类的东西,但由于我正在现有的代码库中工作,因此还需要在不同的位置实现此更改.
我发现的另一种方法是通过跟踪父组件状态中的输入字段状态来将输入字段的值传递给父组件,尽管这显然违反了关注点分离的原则:
父组件
export const ParentComponent = React.createClass({
getInitialState() {
return {
inputFieldValue: undefined
}
},
onChange(change) {
this.setState(inputFieldValue);
},
render() {
return (
<Search
onChange={this.onChange}
inputFieldValue={this.state.inputFieldValue}
/>
}
}
withTracker HOC
import { CollectionAPI } from '../arbitrary_meteormongo_collection';
export const WriteableConnectionToCollection = withTracker(props => {
let connection = Meteor.subscribe('COLLECTION_NAME.searchByName', this.props.inputFieldValue);
let isLoading = connection.ready();
return {
...props,
isLoading: isLoading,
collection: CollectionAPI.find().fetch()
}
});
输入字段组件
import { WriteableConnectionToCollection } from './connections/writeableconnection.js';
const InputFieldComponent = React.createClass({
render() {
<InputField
onInputChange={this.props.onChange}
/>
}
}
export default WritableConnectionToCollection(InputFieldComponent);
这是使用这个特定的包/框架组合做事情的唯一方法还是有一个我没有看到的更简单的方法?
最佳答案
如Christian Fritz had mentioned在我原来的问题下的评论中,我可以使用 ReactiveVar 来将输入传入和传出我的连接组件:
export const WritableConnection = function (subscriptionName, collectionAPI) {
/**
* ReactiveVar must be outside of withTracker. If the it was inside withTracker's scope,
* anytime a user would use .set(ANY_VALUE), it would overwrite whatever was in it first,
* and then re-initialize.
**/
const input = new ReactiveVar(undefined);
return withTracker(props => {
const connection = Meteor.subscribe(subscriptionName, input.get());
const isLoading = connection.ready();
return {
...props,
isLoading: isLoading,
collection: collectionAPI.find().fetch(),
setSearchText: (text) => input.set(text),
getSearchText: () => input.get()
}
})
}
关于reactjs - 是否可以直接从其低阶组件将数据传递到 withTracker ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51851675/
我是一名优秀的程序员,十分优秀!