每当我收到一个新的即将到来的道具时,我想改变当地的状态。为此,我使用lifecycle
库中的Recompose
HOC。但它并不像我想象的那么简单。我要么永远设置值,要么在使用回调时发生堆栈溢出。
import { connect } from 'react-redux';
import { withState, withProps, lifecycle, compose } from 'recompose';
import { selectors, testDelete, testSubscribe } from 'ducks/entities/tests';
import { Tests } from 'components/tests/all-tests';
export default compose(
connect(selectors.tests, {
onTestDelete: testDelete,
onTestSubscribe: testSubscribe,
}),
withState('isDeleteModalOpen', 'setDeleteModalShow', false),
withState('idToDelete', 'setIdToDelete', 0),
withProps(
({
tests,
idToDelete,
setIdToDelete,
setDeleteModalShow,
onTestDelete,
onTestSubscribe,
}) => ({
tests: tests.map((t) =>
t.merge({
onDeleteModalShow: () => {
setDeleteModalShow(true);
setIdToDelete(t.get('id'));
},
onSubscribe: () => onTestSubscribe(t.get('id')),
}),
),
onDeleteModalHide: () => setDeleteModalShow(false),
onDelete: () => onTestDelete(idToDelete),
}),
),
lifecycle({
componentWillReceiveProps({ setDeleteModalShow }) {
setDeleteModalShow(false); // Not workding "Maximum update depth exceeded"
this.setState({
isDeleteModalOpen: false,
}); // now working
},
}),
)(Tests);
答案 0 :(得分:2)
有点老问题,但答案很简单。
如果您设置的值已经是您想要的值,请不要更改状态。在您的代码中,您可以更改lifecycle
增强器以检查isDeleteModalOpen
是否已经为假,如下所示:
lifecycle({
componentWillReceiveProps({ setDeleteModalShow, isDeleteModalOpen }) {
if (isDeleteModalOpen) setDeleteModalShow(false);
},
}),
这样,你的componentWillReceiveProps
函数会弹出两次,第二次不会执行任何操作。
请注意,此组件上的任何道具更改都会将isDeleteModalOpen
值设置为false。