gpt4 book ai didi

reactjs - 在 React HOC 中使用 Redux connect

转载 作者:行者123 更新时间:2023-12-01 22:06:25 25 4
gpt4 key购买 nike

我已经为 sessionTimeout 使用react HOC。现在我想 Redux connect 以使用 redux action 方法。

当我调用方法 this.props.actions.logout 时,它会抛出错误 Undefined。

我想如何在我的 HOC 中连接 redux

HOC

import React from 'react';
import { Modal } from 'antd';
import * as actions from '../../actions';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'

export default function(ComposedClass){
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
warningTime: 4000,
signoutTime: 5000,
};
}

componentDidMount() {
this.events = [
'load',
'mousemove',
'mousedown',
'click',
'scroll',
'keypress'
];

for (var i in this.events) {
window.addEventListener(this.events[i], this.resetTimeout);
}

this.setTimeout();
}

clearTimeoutFunc = () => {
if (this.warnTimeout) clearTimeout(this.warnTimeout);
if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
};

setTimeout = () => {
this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
};

resetTimeout = () => {
this.clearTimeoutFunc();
this.setTimeout();
};

warn = () => {
Modal.warning({
title: 'Session Timeout',
content: 'Your session is about to expire in 1 mintue',
});
};

logout = () => {
this.props.actions.logout()
};

render() {

return (
<div>
<ComposedClass {...this.props} />
</div>
);

}
}
}

最佳答案

您可以在 HOC 中连接组件并从中返回连接的组件

export default function(ComposedClass){

class Component extends React.Component {
constructor(props) {
super(props);
this.state = {
warningTime: 4000,
signoutTime: 5000,
};
}

componentDidMount() {
this.events = [
'load',
'mousemove',
'mousedown',
'click',
'scroll',
'keypress'
];

for (var i in this.events) {
window.addEventListener(this.events[i], this.resetTimeout);
}

this.setTimeout();
}

clearTimeoutFunc = () => {
if (this.warnTimeout) clearTimeout(this.warnTimeout);
if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
};

setTimeout = () => {
this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
};

resetTimeout = () => {
this.clearTimeoutFunc();
this.setTimeout();
};

warn = () => {
Modal.warning({
title: 'Session Timeout',
content: 'Your session is about to expire in 1 mintue',
});
};

logout = () => {
this.props.actions.logout()
};

render() {

return (
<div>
<ComposedClass {...this.props} />
</div>
);

}
}
return connect(mapStateToProps, mapDispatchToProps)(Component)
}

关于reactjs - 在 React HOC 中使用 Redux connect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51535377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com