【问题标题】:react-redux with thunk - getState is not a functionreact-redux with thunk - getState 不是函数
【发布时间】:2018-01-31 11:04:03
【问题描述】:

我目前收到错误 TypeError: getState is not a function 我正在尝试类似于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 is not a function

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

【问题讨论】:

  • 好吧,当你调用它时,你没有向 fetchCategoriesIfNeeded 传递任何东西,所以当它试图调用 getState 时它会连枷。
  • 我猜(我们看不到this.props.dispatch,但这个名字让我相信)你的意思是this.props.dispatch(fetchCategoriesIfNeeded)
  • 我正在使用 thunk 中间件。我稍微更改了我的代码,但现在它说调度不是一个函数。

标签: javascript asynchronous react-redux getstate


【解决方案1】:

您调用调度的方式看起来有些奇怪。

您也应该使用mapDispatchToProps 函数。

例如。像这样:

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


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

和:

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

【讨论】:

    【解决方案2】:

    改变

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

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

    您的动作创建者需要返回一个动作(也就是一个带有type 键的对象)或函数(由 redux-thunk 提供)。您的函数签名让您传入两个参数,dispatchgetState,而第二个函数签名不接受任何参数,但返回函数确实接受 dispatchgetState,它们由 redux-thunk 提供。

    你也可以把它写出来以避免这样的混乱

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

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2017-10-31
      • 1970-01-01
      • 2020-03-25
      • 2017-04-30
      • 2021-04-26
      • 2017-06-09
      • 2020-06-11
      • 2019-02-02
      相关资源
      最近更新 更多