是否可以通过 Redux connect()
函数扩展正在连接的组件?例如,如果我在 form-container.js
内并且我正在使用
const FormContainer = connect(
mapStateToProps,
mapDispatchToProps
)(Form)
有没有办法重写一些这样的方法:
FormContainer.componentDidMount = () => ...
或者添加自定义功能?
最佳答案
您可以为此使用高阶组件。我借用了这个例子 this article
function HigherOrderComponent(WrappedComponent) {
return class NewComponent extends React.Component {
constructor() {
super(props)
this.customMethod = this.customMethod.bind(this)
}
customMethod() {
console.log('You called an injected method');
}
render() {
return <WrappedComponent {...this.props} customMethod={this.customMethod} />
}
}
}
如何使用此自定义方法:
import HigherOrderComponent from './HigherOrderComponent'
class MyComponent extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.props.customMethod()
}
render() {
...
}
}
const MutatedComponent = HigherOrderComponent(MyComponent)
const ConnectedComponent = connect(
mapStateToProps,
mapDispatchToProps
)(MutatedComponent)
据我所知,你不能重写 React 组件的生命周期方法。但是您可以使用 HoC 注入(inject)方法。
关于javascript - 扩展 redux connect() 接收到的 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40994351/