Redux thunk-如何防止它发出不必要的API请求?

山征服者

我有这样的action.js文件:

import axios from 'axios';

export const SEARCH_TERM = 'SEARCH_TERM';
export const SAVE_SEARCH = 'SAVE_SEARCH';

export function search(query) {
  const githubApi = `https://api.github.com/search/repositories?q=${query}&sort=stars&order=desc`;
  const request = axios.get(githubApi);
  return (dispatch) => {
    request.then(({ data: dataFromGithub }) => {
      dispatch({ type: SEARCH_TERM, payload: query });
      dispatch({ type: SAVE_SEARCH, payloadOne: query, payloadTwo: dataFromGithub });
    });
  };
}

使用reduce,我保存到redux来存储用户输入的所有搜索词。然后,我向github api发出请求,并保存响应数据。

现在我有一个问题,我真的还不知道该如何处理。

我该如何编写代码来检查用户之前是否已经搜索过该查询,在这种情况下,我的应用不会将请求发送到github api。

我该怎么做以及该把逻辑放在哪里?有任何想法吗?


编辑:感谢@klugjo!由于他的暗示,我编写了确实有效的代码。

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import _ from 'lodash';
import logo from './logo.svg';
import './style.css';

import SearchBar from '../SearchBar';

import { search } from '../../actions/';

class App extends Component {
  startSearch(query) {
    const storedTerms = this.props.storedSearchTerms;
    let foundDuplicate = false;

    if (storedTerms.length === 0) {
      return this.props.search(query);
    }

    if (storedTerms.length !== 0) {
      const testDuplicate = storedTerms.map(term => term === query);
      foundDuplicate = testDuplicate.some(element => element);
    }

    if (foundDuplicate) {
      return false;
    }

    return this.props.search(query);
  }

  render() {
    const searchDebounced = _.debounce(query => this.startSearch(query), 2000);
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started...
        </p>
        <SearchBar handleSearchQueryChange={searchDebounced} />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    storedSearchTerms: state.searchTerm,
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ search }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
克鲁格霍

您将必须从React组件内部进行检查。

根据您的代码,我会说您正在保存已执行的查询列表:

dispatch({ type: SEARCH_TERM, payload: query });

在您的.jsx容器中,仅当过去的查询列表中不存在该查询时,才执行搜索操作。

我认为,从动作创建者内部传递或访问您的redux状态是一种反模式。您可以在此处阅读更多内容

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章