我正在使用 Redux-thunk 中间件开发 React-Redux 应用程序。当我尝试在 actions.js 文件中执行名为 removeStock() 的函数时,收到一条错误消息:“TypeError: Dispatch is not a function”:
action.js
export const deletePinnedStock = (user_id, stock_name, stock_id) => {
return dispatch => {
ApiService.delete("/users/" + user_id + "/stocks/" + stock_id)
.then(response => {
dispatch(removeStock(stock_name))
console.log('here is the', response)
}).catch((errors) => {
console.log(errors)
})
}
}
removeStock() 看起来像这样:
export const removeStock = (stock_name) => {
return {
type: 'REMOVE_PINNED_STOCK',
stock_name: stock_name
}
}
与我的 reducer 中的“REMOVE_PINNED_STOCK”操作相对应的 case 语句如下所示:
reducer.js
case 'REMOVE_PINNED_STOCK':
return {
...state,
stocksData: {
...state.stocksData.delete((stock) => stock.name === action.stock_name)
}
}
我不知道为什么我不能在我的deletePinnedStock() 函数中调度removeStock() 函数。在我的 action.js 文件的其他地方,我调度函数没有任何问题。
编辑#1: deletePinnedStock 在我的组件中定义如下:
stockCard.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPinnedStocks, deletePinnedStock, fetchStockData } from
'../redux/modules/Stock/actions';
import '../styles/spin.css';
import Panel from 'react-uikit-panel';
class StockCard extends Component {
render() {
const user_id = localStorage.getItem('currentUser_id')
const stock = this.props.stock //should be the stockObj keyed by name
if (!stock) {
return null
} else {
return (
<Panel col='1-2' box title={stock.name} margin='bottom' context='primary'>
<div>
Open: {stock.openingPrice}
</div>
<div>
Close: {stock.closingPrice}
</div>
<div>
Low: {stock.low}
</div>
<div>
High: {stock.high}
</div>
<div>
Trading Volume: {stock.volume}
</div>
<button type="submit"
onClick={deletePinnedStock(user_id, stock.name, stock.id)}>Remove</button>
</Panel>)
}
}
}
function mapStateToProps(state) {
return {
currentUser: state.auth.currentUser,
stocksData: state.stock.stocksData
}
}
export default connect(mapStateToProps, { fetchPinnedStocks,
deletePinnedStock, fetchStockData })(StockCard);
最佳答案
通过直接调用 deletePinnedStock
,您只是将其作为函数调用,而不是将其分派(dispatch)到 redux 存储。当您将操作创建者传递给 connect()
时,它会作为 Prop 添加到您的组件中,并且该 Prop 是映射到 dispatch
的 Prop 。
简而言之,替换
onClick={deletePinnedStock(user_id, stock.name, stock.id)}
与
onClick={this.props.deletePinnedStock(user_id, stock.name, stock.id)}
关于javascript - js文件类型错误: Dispatch is not a Function in actions.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45404816/