javascript - 使用 debounce 将 React 状态同步到 Meteor 集合

标签 javascript meteor reactjs debouncing

我的 Meteor + React 应用程序中有一个文本框。我想将其值同步到 Mongo 集合。但是,我不想在每次击键后更新集合,仅当用户停止输入几秒钟时才更新。

我的 render() 函数中的文本框如下所示:

<input type="text" ref="answer" onChange={this.onChange} value={this.state.someValue} />

我将文本框值存储在 this.state 而不是 this.data 中,因为 this.data 反射(reflect)了 Mongo 集合,它可能有还没有更新。

到目前为止,所有这些都有效。

问题:

如果另一个客户端更新集合,我希望文本框显示更新后的值。为此,我必须更新 getMeteorData() 函数内的 this.state,但这是不允许的,并且我得到一个错误:“调用 setState inside getMeteorData can result在无限循环中”

现在我有一个变通方法,我手动更新 componentDidMount()getMeteorData() 中的文本框值,但感觉很老套,我不喜欢它完全没有。

有更好的方法吗?如果我保证我会成为一个好 child 并且表现得很好,我是否可以在 getMeteorData() 中强制更新状态?

最佳答案

我会完全摆脱 getMeteorData 并转向 createContainer .大多数时候数据流变得清晰和简单,包括这个特定的案例。开始了。

首先,创建一个容器来获取数据。

export default theContainer = createContainer(() => {
  // Subscribe to the publication which publishes the data.
  const subscription = Meteor.subscribe(...);
  // Derive the data for the input box and form the props to pass down.
  const props = {
    answer: getAnswer(subscription)
  };
  return props;
}, theComponent);

theContainer 充当容器组件,通过 props 将包含的数据传递给展示组件 theComponent。请注意,提供给 createContainer 的函数是响应式的,这意味着对该函数中响应式数据源的更改会触发重新运行并导致重新呈现 theComponent

现在我们都全副武装了。由于 Mongo 集合(确切地说是 Minimongo)中的数据是通过向下传递的 props 同步的,theComponent 通过 prop transition 意识到同步。

export default class theComponent extends React.Component {
  ...

  componentWillReceiveProps(nextProps) {
    if (this.props.answer !== nextProps.answer) {
      this.setState({
        answer: nextProps.answer
      });
    }
  }

  render() {
    return <input value={this.state.answer} onChange={this.onChange} />;
  }
}

当发生这种转换时,即将到来的值会更新为状态,并且此受控组件将根据更新后的新值呈现输入。

另一方面,当用户开始输入时,更改处理程序 this.onChange 将用户的输入更新为每个按键的状态,因为这是一个受控组件。但是,处理程序仅在预设持续时间过去后才更新 Mongo 集合(同样,确切地说是 Minimongo)以保存数据传输。

关于javascript - 使用 debounce 将 React 状态同步到 Meteor 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33568900/

相关文章:

javascript - 使用 css (SASS) 压缩 compass 等 js 文件

node.js - Meteor SSR "Error: Can' t 渲染未定义”

reactjs - 当我尝试测试一个非常简单的组件时,出现 contextTypes 错误

javascript - 如何将 redux-thunk Action Creator 变成 Promise?

javascript - jQuery 同位素 - 样式事件类别

javascript - 如何在 Angular 数据中显示或任何原始 html?

javascript - 使用 Javascript 获取为某个域打开的所有窗口

javascript - meteor .js : getting a sum of collection field

meteor - 如何将 Handlebars isEq 助手转换为 Meteor 中的空格键?

javascript - 是否可以在不丢失对象验证的情况下为有条件要求的对象数组编写自定义 Prop 类型验证器?