我是 react-redux 的新手,我正在使用 react-thunk 中间件。每当我尝试运行我的 action creator(通过按下我的按钮)时,我都会收到错误“Uncaught TypeError: dispatch is not a function”。有人知道这是怎么回事吗?
src/actions/index.js
function editUserName (newUserName) {
return {
type: 'CHANGE_USER_NAME',
newUserName: newUserName
}
}
export function editUserNameDelegate () {
return function (dispatch, getState) {
return dispatch(editUserName("thunkUser"))
}
}
src/containers/admin.js
import { editUserNameDelegate } from '../actions/index'
...
<input type="button" onClick={ editUserNameDelegate() } value="edit UserName" />
最佳答案
您正在 render
中执行 editUserNameDelegate
函数,而不是将其作为 onClick
处理程序传递。您需要 onClick={editUserNameDelegate}
。
此外,如果您以这种方式编写它,则需要确保该函数在您调用它时绑定(bind)到分派(dispatch)。你可以这样做:
导出默认连接(null, {editUserNameDelegate})(MyComponent)
然后在渲染函数中传递 onClick={this.props.editUserNameDelegate}
。
关于javascript - dispatch is not a function 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41887069/