React-Redux与Thunk - getState不是一个函数

4
我目前遇到了 TypeError: getState 不是函数的错误。 我正在尝试类似于此示例的操作:http://redux.js.org/docs/advanced/AsyncActions.html 在 action.js 中出现了该错误。
export const fetchCategoriesIfNeeded = (dispatch, getState) => {
    if(shouldFetchCategories(getState())){
        return dispatch(fetchCategories())
    }
}

App.js

  componentDidMount(){
    this.props.dispatch(fetchCategoriesIfNeeded())
  }

...

const mapStateToProps = (state, props) => {
  return {
    isFetching: state.isFetching,
    categories: state.categories
    }
}

reducer.js

function data (state = initialState, action){
    switch(action.type){
        case RECEIVE_CATEGORIES:
            return {
                ...state,
                isFetching: false,
                categories: action.categories
            }
        case REQUEST_CATEGORIES:
            return {
                ...state,
                isFetching: true
            }
        default:
            return state
    }
    return state
}

为了可读性,我省略了部分代码。

我也尝试过这种方法,但是收到了 TypeError: dispatch 不是函数 的错误信息。

export function fetchCategoriesIfNeeded(){
    return(dispatch, getState) =>{
        var state = getState()
        if(shouldFetchCategories(state)){
            dispatch(fetchCategories())
        }
    }
}

1
好的,当您调用fetchCategoriesIfNeeded时没有传递任何内容,因此它尝试调用getState时失败是有道理的。 - Dave Newton
我猜测(我们看不到 this.props.dispatch,但名称让我相信)你的意思是 this.props.dispatch(fetchCategoriesIfNeeded) - user4639281
我正在使用thunk中间件。 我稍微改了一下我的代码,但现在它说dispatch不是一个函数。 - Grant M
https://dev59.com/C1sV5IYBdhLWcg3w4iP- - Grant M
2个回答

5

修改

export const fetchCategoriesIfNeeded = (dispatch, getState) => {

export const fetchCategoriesIfNeeded = () => (dispatch, getState) => {

你的 action creator 需要返回一个 action 对象(具有 type 属性)或函数(由 redux-thunk 提供)。你的函数签名需要传入两个参数 dispatchgetState,而第二个函数签名不需要参数,但是返回的函数需要 dispatchgetState,这些都由 redux-thunk 提供。

为了避免混淆,你也可以这样写:

export const fetchCategoriesIfNeeded = () => {
    return (dispatch, getState) => {
       // Do stuff
    }
}

希望这能帮到您!

0

看起来你在调用dispatch的方式上做了一些奇怪的事情。

你应该也使用一个mapDispatchToProps函数。

例如,像这样:

const mapDispatchToProps = (dispatch, props) => {
   return {
       onUpdate: dispatch(fetchCategories())
    }
}


const mapStateToProps = (state, props) => {
  return {
    isFetching: state.isFetching,
    categories: state.categories
    }
}

和:

  componentDidMount(){
    this.props.onUpdate(); 
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接