react-redux with thunk - getState 不是一个函数



我当前收到错误类型错误:getState 不是一个函数 我正在尝试类似于 http://redux.js.org/docs/advanced/AsyncActions.html 示例

操作.js - 此处发生错误

export const fetchCategoriesIfNeeded = (dispatch, getState) => {
if(shouldFetchCategories(getState())){
return dispatch(fetchCategories())
}
}

应用.js

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

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

减速器.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
}

为了便于阅读,省略了一些代码。

我也试过这个并收到类型错误:调度不是一个函数

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

更改

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
}
}

希望对您有所帮助!

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

您还应该使用mapDispatchToProps函数。

例如,像这样:

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

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

和:

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

最新更新