我有这样的 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 });
});
};
}
我正在使用 reducer 保存到 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
容器中,仅当您过去的查询列表中不存在该查询时才执行搜索操作。
在我看来,从 action creator 中传递或访问你的 redux state 是一种反模式。您可以阅读更多关于 here 的内容.
关于javascript - Redux thunk - 如何防止它发出不必要的 API 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47973117/