Gra*_*t M 4 javascript asynchronous getstate react-redux
我目前收到错误 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())
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序.js
componentDidMount(){
this.props.dispatch(fetchCategoriesIfNeeded())
}
Run Code Online (Sandbox Code Playgroud)
...
const mapStateToProps = (state, props) => {
return {
isFetching: state.isFetching,
categories: state.categories
}
}
Run Code Online (Sandbox Code Playgroud)
减速器.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
}
Run Code Online (Sandbox Code Playgroud)
为了可读性省略了一些代码。
我也尝试过这个并收到 TypeError:dispatch is not a function
export function fetchCategoriesIfNeeded(){
return(dispatch, getState) =>{
var state = getState()
if(shouldFetchCategories(state)){
dispatch(fetchCategories())
}
}
}
Run Code Online (Sandbox Code Playgroud)
改变
export const fetchCategoriesIfNeeded = (dispatch, getState) => {
到
export const fetchCategoriesIfNeeded = () => (dispatch, getState) => {
你的动作创建者需要返回一个动作(又名带有type键的对象)或函数(由 redux-thunk 提供)。您的函数签名让您传入两个参数,dispatch而getState第二个函数签名不带任何参数,但返回函数确实需要dispatch和getState,这是由 redux-thunk 提供的。
您也可以将其写出来以避免像这样混淆
export const fetchCategoriesIfNeeded = () => {
return (dispatch, getState) => {
// Do stuff
}
}Run Code Online (Sandbox Code Playgroud)
希望有帮助!
| 归档时间: |
|
| 查看次数: |
3003 次 |
| 最近记录: |