如果我创建自己的mapDispatchToProps函数,它将无法正常工作。如果我提供一个简单的对象进行连接,那么它确实可以工作,但是我需要分派功能..例如,每页的翻译加载量,我在这里做错了吗?
const mapStateToProps = (state) => {
const { isFetching, lastUpdated, items, errors } = state.transactions; // fetch from redux state ;)
return {
translate: getTranslate(state.locale),
isFetching,
lastUpdated,
items,
errors
}
}
const mapDispatchToProps = dispatch => {
return {
fetchTransactionsIfNeeded,
invalidateList
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Transactions);
下面的代码有效
const mapStateToProps = (state) => {
const { isFetching, lastUpdated, items, errors } = state.transactions; // fetch from redux state ;)
return {
translate: getTranslate(state.locale),
isFetching,
lastUpdated,
items,
errors
}
}
export default connect(mapStateToProps, {
fetchTransactionsIfNeeded,
invalidateList
})(Transactions);
根据redux文档
[mapDispatchToProps(dispatch,[ownProps]):dispatchProps](对象或函数):如果传递了一个对象,则假定其中的每个函数都是Redux操作创建者。一个具有相同功能名称的对象,但每个动作创建者都包装在一个调度调用中,以便可以直接调用它们,这些对象将合并到组件的props中。
如果传递了一个函数,它将作为第一个参数被分配。由您决定是否返回一个对象,该对象以某种方式使用调度以自己的方式绑定动作创建者。(提示:您可以使用Redux中的bindActionCreators()帮助器。)
在第一种情况下,当您实现mapDispatchToProps时,您将返回一个普通对象,但是您需要在其中使用dispatch,因为redux本身并不将其视为动作创建者。
你会像这样实现
const mapDispatchToProps = dispatch => {
return {
fetchTransactionsIfNeeded: (...args) => {
dispatch(fetchTransactionsIfNeeded(...args))
},
invalidateList: (...args) => {
dispatch(invalidateList(...args))
},
}
}
否则不要将其创建为函数,而只是创建一个对象
const mapDispatchToProps = {
fetchTransactionsIfNeeded,
invalidateList
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句