gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:01:45 24 4
gpt4 key购买 nike

我目前收到错误 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())
}
}
}

最佳答案

改变

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

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

你的 Action 创建者需要返回一个 Action (也就是一个带有 type 键的对象)或函数(由 redux-thunk 提供)。你的函数签名让你传入了两个参数,dispatchgetState 而第二个函数签名不带参数,但返回函数确实带 dispatchgetState,由redux-thunk提供。

你也可以把它写出来,以免像这样混淆

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

希望对您有所帮助!

关于javascript - react-redux with thunk - getState 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45829850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com