如何在React中限制setState?

时间:2017-08-21 10:51:33

标签: reactjs graphql

  1. 有一个SearchBar组件会更改整个组件状态,然后Whole将重新呈现,这会导致子组件PlayerListWithQuery使用新状态重新呈现同样。

  2. PlayerListWithQuery组件根据传递给此组件的搜索内容查询graphql服务器

  3. 问题是我不想经常执行查询但必须立即更改输入值,我该如何解决这个问题。

    import PlayerListWithQuery from './PlayerListWithQuery.js'
    class Whole extends Component {
      constructor(props) {
        super(props);
        this.state = {
          searchContent: '',
        };
      }
      handleChange = val => {
        this.setState({
          searchContent: val,
        });
      };
    
      render() {
        return (
          <div>
            <SearchBar
              placeholder="Id"
              onChange={this.handleChange}
              value={this.state.searchContent}
            />
            <PlayerListWithQuery searchContent={this.state.searchContent} {...this.props} />
          </div>
        );
      }
    }
    
    export default Whole;
    

    // PlayerListWithQuery.js

    const PlayerListWithQuery = graphql(QUERY_SINGLE_PLAYER, {
      options: props => ({
        fetchPolicy: 'network-only',
        variables: {
          id: props.searchContent,
        },
      }),
    })(PlayerList);
    
    export default PlayerListWithQuery;
    

1 个答案:

答案 0 :(得分:0)

我正在使用lodash's debounce来做同样的事情。或者您可以实现debounce这样的功能(credit

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};