我有,应该是一个简单的问题,当用户导航到特定路线时,该组件触发初始函数调用以通过史诗中的redux-observable
通过ID获取用户。但是,如果用户离开页面然后返回,我需要能够根据路由参数重新加载页面。
我有一个利用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). Render methods should be a pure function of props and state.
^这是因为我的if
语句检查用户id与params id。
是否需要将此组件转换为类,以便利用可以防止此错误发生的其他生命周期方法并相应地运行我的功能?
函数组件应该是纯粹的,您可以将它们视为类组件的“render”方法。
您可以使用类组件并在componentDidMount
/ componentDidUpdate
中执行副作用,也可以使用useEffect
的钩子。
我猜这个问题与ProfilePage
有关。添加错误Cannot update during an existing state transition (such as withinrender).
主要是在作为异步方法的setState,另一个setState被调用时抛出的。对于您的情况,它是一个功能组件,您在render方法中使用它。所以基本上每次你的组件重新呈现时都会调用调用该函数的ProfilePage函数。因此,您可能希望将ProfilePage更改为react组件,并使用生命周期方法(如componentDidMount
)来解决您的问题。或者,如果您使用的是反应16或更高版本,请使用带有useEffect的钩子。