Redux:从另一个动作创建者调用一个动作

duh*_*ime 12 reactjs redux redux-thunk react-redux

我正在开发一个Redux应用程序,其中许多过滤器组件可以改变要执行的搜索的性质.每当其中一个过滤器组件的状态发生变化时,我想重新运行搜索操作.但是,我似乎无法正确地调用每个过滤器组件的搜索操作.

这是主要的搜索操作:

// actions/search.js
import fetch from 'isomorphic-fetch';
import config from '../../server/config';

export const receiveSearchResults = (results) => ({
  type: 'RECEIVE_SEARCH_RESULTS', results
})

export const searchRequestFailed = () => ({
  type: 'SEARCH_REQUEST_FAILED'
})

export const fetchSearchResults = () => {
  return (dispatch, getState) => {
    // Generate the query url
    const query = getSearchQuery();  // returns a url string
    return fetch(query)
      .then(response => response.json()
        .then(json => ({
          status: response.status,
          json
        })
      ))
      .then(({ status, json }) => {
        if (status >= 400) dispatch(searchRequestFailed())
        else dispatch(receiveSearchResults(json))
      }, err => { dispatch(searchRequestFailed()) })
  }
}
Run Code Online (Sandbox Code Playgroud)

fetchSearchResults当我从连接的React组件调用它时工作正常.但是,我无法从以下操作创建者调用该方法(这是过滤器操作创建者之一):

// actions/use-types.js
import fetchSearchResults from './search';

export const toggleUseTypes = (use) => {
  return (dispatch) => {
    dispatch({type: 'TOGGLE_USE_TYPES', use: use})
    fetchSearchResults()
  }
}
Run Code Online (Sandbox Code Playgroud)

运行此产生:Uncaught TypeError: (0 , _search2.default) is not a function.我跑dispatch(fetchSearchResults())进去的时候也是这样toggleUseTypes.

我肯定犯了一个菜鸟错误 - 有谁知道如何解决这个问题并fetchSearchResultsactions/use-types.js行动中调用方法?我非常感谢其他人可以提出的关于这个问题的建议!

Cor*_*son 28

我看到2个错误

  1. 您正在错误地导入fetchSearchResults函数
    • 这是TypeError _search2.default的来源.
    • Uncaught TypeError: (0 , _search2.default) is not a function
  2. 您错误地调度了fetchSearchResults操作/ thunk

错误1:导入错误

// This won't work. fetchSearchResults is not the default export
import fetchSearchResults from './search';
// Use named import, instead.
import {fetchSearchResults} from './search';
Run Code Online (Sandbox Code Playgroud)

错误2:操作使用不正确

// This won't work, it's just a call to a function that returns a function
fetchSearchResults()
// This will work. Dispatching the thunk
dispatch(fetchSearchResults())
Run Code Online (Sandbox Code Playgroud)

  • 阿门,非常感谢@CoryDanielson!我会在5分钟内接受这个(因为某种原因让人等待). (3认同)
  • 哦,这太好了。我花了一点谷歌搜索来弄清楚如何使用“redux-thunk”从不同文件中的另一个调用一个动作创建者,现在这很有意义。谢谢! (3认同)