gpt4 book ai didi

reactjs - 是否可以直接从其低阶组件将数据传递到 withTracker ?

转载 作者:行者123 更新时间:2023-12-03 14:12:35 28 4
gpt4 key购买 nike

我正在使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com