Api 调用没有在带有去抖动的 redux 动作中启动

Api call not firing up in redux action with debouce

我正在尝试使用我自己的纯 js 函数实现去抖动,以便使用 axios POST 请求调用动作文件中的动作。

输入框组件中的以下代码

import React, { useState, useCallback } from 'react'
import { searchDrug } from '../../actions/drug-interaction'

function CustomInputSearch(props) {
  const { handleSelectInput } = props


  const apiCall = (value) => {
    searchDrug(value)
    
}

  const debounce = (apiFunc, delay) => {
    let inDebounce
    return function () {
      const context = this
      const args = arguments 
      clearTimeout(inDebounce)
      inDebounce = setTimeout(() => apiFunc.apply(context, args), delay)
    }
  }

  const optimizedVersion = debounce(apiCall, 500)

  const handleChange = (e) => {
    optimizedVersion(e.target.value)
  }

  return (
    <div>
      <input
        className='form-control'
        placeholder='Search Drug...'
        onKeyUp={handleChange}
      />
    </div>
  )
}

export default CustomInputSearch

忽略不必要的导入。

下面的代码是动作文件。

export const searchDrug = (drug) => {
    const params = {
        "start": drug,
        "limit": 100
    }
    let axiosConfig = {
        headers: {
            // 'Access-Control-Allow-Origin': '*'
        }
    }
    return  (dispatch) => {
        dispatch({ type: 'DRUG_LIST_NOTIFY', payload: { drugListLoading: true } })
         axios.post(`${API_URL}/drug/autocomplete`, params, axiosConfig)
            .then((response) => {
                dispatch({
                    type: 'DRUG_LIST',
                    payload: { response: response.data, drugListLoading: false }
                })
            })
            .catch((error) => {
                dispatch({ type: 'DRUG_LIST_NOTIFY', payload: { drugListLoading: false } })
                if (error.response && error.response.status === 401) {
                    window.open('/?src=auth-error', '_self')
                }
            });
    };
}

但是我在 browser.Im 的网络选项卡中没有看到任何请求,也提前在 redux store.Thanks 中使用了 composedWithDevtools

这是因为你的searchDrug动作必须来自dispatch而不是直接调用它。

import React, { useState, useCallback } from 'react'
import { useDispatch } from 'react-redux'
import { searchDrug } from '../../actions/drug-interaction'

function CustomInputSearch(props) {
  const { handleSelectInput } = props
  const dispatch = useDispatch()

  const apiCall = (value) => {
    dispatch(searchDrug(value))
  }
  ...