Redux shorthand `mapDispatchToProps` returns 未定义 `async` 动作/thunk
Redux shorthand `mapDispatchToProps` returns undefined for `async` actions / thunks
我遇到了我认为可能是错误但可能是我的理解的问题。
基本上 async
action
returns 的 import
在 Redux
容器内未定义,但我知道导入没问题(文件存在,这是正确的情况等等)。
仔细观察,问题似乎是在我迁移到容器中的 shorthand 对象表示法时开始的,这是一个示例:
thunks.js
import { anAsyncFunc } from './anotherFile'
export const aThunk = () => async (dispatch, getState) => {
await dispatch(anAsyncFunc)
return dispatch(someOtherAsyncFunc)
}
containerThatDoesntWork.js
import { aThunk } from './thunks.js'
import MyComponent from './MyComponent'
console.log(aThunk) // undefined
const mapDispatchToProps = {
aThunk
}
containerThatDoesWork.js
import { aThunk } from './thunks.js'
import MyComponent from './MyComponent'
console.log(aThunk) // undefined
const mapDispatchToProps = dispatch => ({
aThunk: () => {
console.log(aThunk) // return async function (dispatch, getState) { ... }
return dispatch(aThunk())
}
})
在这两种情况下,如果我在 container
中 console.log(aThunk)
我得到未定义,我认为这与 async
函数的模块解析有关?
然而,在第二个示例中,导入被显式包装在一个函数中,组件是快乐的,而在 shorthand 表示法中它不是(PropTypes 验证失败)。
有人知道解决这个问题的方法吗?还是在对象 shorthand 表示法中对 mapDispatchToProps
的限制?
const mapDispatchToProps = {
aThunk
}
和
const mapDispatchToProps = dispatch => ({
aThunk: () => dispatch(aThunk())
})
应该以同样的方式行事。如果 mapDispatchToProps
是一个对象,属性会自动转换为 () => dispatch(action)
。两者都应该导致 aThunk
支持 returns aThunk()(dispatch)
的结果,即承诺。
这里是a demo。
命名导入可以在模块范围内未定义但在函数范围内存在的唯一原因是在延迟访问依赖项时解决了循环依赖项。用 dispatch => ...
完成的这样的函数包装依赖项是一个已知的解决循环依赖项的方法,幸运的是 mapDispatchToProps
支持它,但最好不要首先使用它们,特别是如果这是'设计使然。
我遇到了我认为可能是错误但可能是我的理解的问题。
基本上 async
action
returns 的 import
在 Redux
容器内未定义,但我知道导入没问题(文件存在,这是正确的情况等等)。
仔细观察,问题似乎是在我迁移到容器中的 shorthand 对象表示法时开始的,这是一个示例:
thunks.js
import { anAsyncFunc } from './anotherFile'
export const aThunk = () => async (dispatch, getState) => {
await dispatch(anAsyncFunc)
return dispatch(someOtherAsyncFunc)
}
containerThatDoesntWork.js
import { aThunk } from './thunks.js'
import MyComponent from './MyComponent'
console.log(aThunk) // undefined
const mapDispatchToProps = {
aThunk
}
containerThatDoesWork.js
import { aThunk } from './thunks.js'
import MyComponent from './MyComponent'
console.log(aThunk) // undefined
const mapDispatchToProps = dispatch => ({
aThunk: () => {
console.log(aThunk) // return async function (dispatch, getState) { ... }
return dispatch(aThunk())
}
})
在这两种情况下,如果我在 container
中 console.log(aThunk)
我得到未定义,我认为这与 async
函数的模块解析有关?
然而,在第二个示例中,导入被显式包装在一个函数中,组件是快乐的,而在 shorthand 表示法中它不是(PropTypes 验证失败)。
有人知道解决这个问题的方法吗?还是在对象 shorthand 表示法中对 mapDispatchToProps
的限制?
const mapDispatchToProps = {
aThunk
}
和
const mapDispatchToProps = dispatch => ({
aThunk: () => dispatch(aThunk())
})
应该以同样的方式行事。如果 mapDispatchToProps
是一个对象,属性会自动转换为 () => dispatch(action)
。两者都应该导致 aThunk
支持 returns aThunk()(dispatch)
的结果,即承诺。
这里是a demo。
命名导入可以在模块范围内未定义但在函数范围内存在的唯一原因是在延迟访问依赖项时解决了循环依赖项。用 dispatch => ...
完成的这样的函数包装依赖项是一个已知的解决循环依赖项的方法,幸运的是 mapDispatchToProps
支持它,但最好不要首先使用它们,特别是如果这是'设计使然。