【发布时间】:2018-07-04 08:39:06
【问题描述】:
toggleModal() 函数切换本地状态。调度异步函数后,我想关闭模式。但是我无法访问 dispatch 中的类函数。
可以通过将模式状态移动到商店来解决该问题,但我想将此值保留为类的本地值。
我尝试将模态值作为道具传递,虽然我可以在调度函数中使用 ownProps 访问该值,但它是一个只读值。
import React from 'react'
import { connect } from 'react-redux'
class MyComponent extends React.Component {
constructor(props){
super(props)
this.state = { modal: false }
}
onClick() {
// OPTION (1)
// reduxFunction is not a promise, so then doesn't work
this.props.reduxFunction().then(() => {
this.toggleModal()
})
// OPTION (2)
// This needs to fire after async function
this.toggleModal()
}
// Want to call this function inside dispatch
toggleModal() {
this.setState({ modal: !this.state.modal })
}
render () {}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
reduxFunction: () => {
dispatch('SOME_ASYNC_FUNCTION').then(() => {
// How to call this function?
toggleModal()
// ownProps is read-only, so can't be solved by passing modal as prop
})
}
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(AddInstrument)
【问题讨论】:
-
您将在组件中的某处调用
reduxFunction。有什么理由你不能在那之后马上打电话给toggleModal? -
我更新了代码,但是 this.props.reduxFunction 不是promise,所以它似乎不起作用
标签: javascript reactjs ecmascript-6 redux react-redux