React / Redux-如何根据渲染检查组件渲染后的动作-获取错误

时间:2019-03-28 13:37:17

标签: reactjs redux react-redux redux-observable

我有一个简单的问题,其中,当用户导航到特定路线时,该组件会触发初始功能调用,以通过史诗中的redux-observable通过ID捕获用户。但是,如果用户离开页面然后又回来,我需要能够基于route参数重新加载页面。

我有一个使用HOC来运行render()方法的组件,但它看起来像一个愚蠢的组件:

const ProfilePage = props => {
  const { actions, user, loading } = props;

  // Note: This if statement results in an error
  if (user && user.id !== props.params.id) {
   actions.initAction(props.params.id);
  }

  return (<div>Test</div>);
};

ProfilePage.propTypes = {
  actions: PropTypes.object,
  user: PropTypes.object,
  loading: PropTypes.bool,
};


export default connect(
  state => ({
    user: selectUser(state),
    loading: selectLoading(state),
  }),
  dispatch => ({ actions: bindActionCreators(Actions, dispatch) })
)(
  PureRender(
    onMount(props => props.actions.initAction(props.params.id))(ProfilePage)
  )
);

这会导致错误:

react-dom.development.js?61bb:506 Warning: Cannot update during an existing state transition (such as within渲染). Render methods should be a pure function of props and state.

^发生这种情况是由于我的if语句将用户ID与参数ID进行了比较。

是否需要将该组件转换为类,以便利用其他生命周期方法来防止发生此错误并相应地运行我的功能?

2 个答案:

答案 0 :(得分:1)

功能组件应该是纯组件,您可以将它们视为类组件的“渲染”方法。
您可以在componentDidMount / componentDidUpdate中使用类组件并产生副作用,也可以在useEffect中使用钩子。

hooks useEffect / class cycle methods

答案 1 :(得分:0)

我猜这是ProfilePage的问题。添加了一个错误Cannot update during an existing state transition (such as withinrender).,该错误主要在setState(它是一种异步方法)和另一个setState被调用时引发。对于您的情况,这是一个功能组件,您正在render方法中使用它。因此,基本上每次您的组件重新渲染ProfilePage函数时,该函数就会调用该动作。因此,您可能希望将ProfilePage更改为React组件,并使用生命周期方法(例如componentDidMount)来解决问题。 或者,如果您使用的是React 16或更高版本,请使用带有useEffect的钩子。