2

每次收到即将到来的新道具时,我都想更改本地状态。为此,我使用库中的lifecycleHOC Recompose。但这并不像我想的那么简单。我要么永远设置该值,要么在使用回调时发生堆栈溢出。

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);

4

1 回答 1

2

有点老问题,但答案很简单。

如果您设置的值已经是您想要的值,请不要更改状态。在您的代码中,您可以更改lifecycle增强器以检查 是否isDeleteModalOpen已经为假,如下所示:

lifecycle({
  componentWillReceiveProps({ setDeleteModalShow, isDeleteModalOpen }) {
    if (isDeleteModalOpen) setDeleteModalShow(false);
  },
}),

这样你的componentWillReceiveProps函数会命中两次,第二次它什么也不做。

请注意,此组件上的任何 prop 更改都会将该isDeleteModalOpen值设置为 false。

于 2018-04-17T16:36:15.623 回答