useEffect 中的 Redux 分派导致无限重新渲染
Redux dispatch in useEffect causing infinite rerender
我曾尝试搜索以前的类似问题,但许多答案建议将依赖项数组传递给 useEffect
,我已经这样做了。
这基本上是一个用户的展示页面:
const Profile = ({ currentUser, profileOwner, getProfileInfo, isMine }) => {
useEffect(() => {
getProfileInfo();
}, [profileOwner]);
return (stuff)
}
这是它的容器:
const mapStateToProps = ({ session, users }, ownProps) => ({
currentUser: users[session.id],
profileOwner: users[ownProps.params.userId],
isMine: session.id === parseInt(ownProps.params.userId),
});
const mapDispatchToProps = (dispatch, ownProps) => ({
getProfileInfo: () => dispatch(getProfileInfo(ownProps.params.userId)),
});
我认为这是导致重新渲染的操作:
export const getProfileInfo = (userId) => (dispatch) =>
axios.get(`/api/users/${userId}`).then((res) => res.data)
.then((user) => dispatch(receiveProfileOwner(user)));
如果我从依赖项数组中取出 profileOwner
,则不再有无限循环,但如果我导航到其他用户的个人资料,它就不会获取用户数据。
据我所知, profileOwner
的值在第一次获取后根本不应该改变,所以我仍然很困惑为什么会出现这个问题。
似乎使用 profileOwner
因为依赖是错误的。该组件已经接收到路由参数作为道具,所以我将 useEffect 更改为:
const Profile = ({ currentUser, profileOwner, getProfileInfo, isMine, params: { userId } }) => {
useEffect(() => {
getProfileInfo();
}, [userId]);
有点乱,我希望有比添加更多道具更好的方法来做到这一点,但它确实解决了问题。
我曾尝试搜索以前的类似问题,但许多答案建议将依赖项数组传递给 useEffect
,我已经这样做了。
这基本上是一个用户的展示页面:
const Profile = ({ currentUser, profileOwner, getProfileInfo, isMine }) => {
useEffect(() => {
getProfileInfo();
}, [profileOwner]);
return (stuff)
}
这是它的容器:
const mapStateToProps = ({ session, users }, ownProps) => ({
currentUser: users[session.id],
profileOwner: users[ownProps.params.userId],
isMine: session.id === parseInt(ownProps.params.userId),
});
const mapDispatchToProps = (dispatch, ownProps) => ({
getProfileInfo: () => dispatch(getProfileInfo(ownProps.params.userId)),
});
我认为这是导致重新渲染的操作:
export const getProfileInfo = (userId) => (dispatch) =>
axios.get(`/api/users/${userId}`).then((res) => res.data)
.then((user) => dispatch(receiveProfileOwner(user)));
如果我从依赖项数组中取出 profileOwner
,则不再有无限循环,但如果我导航到其他用户的个人资料,它就不会获取用户数据。
据我所知, profileOwner
的值在第一次获取后根本不应该改变,所以我仍然很困惑为什么会出现这个问题。
似乎使用 profileOwner
因为依赖是错误的。该组件已经接收到路由参数作为道具,所以我将 useEffect 更改为:
const Profile = ({ currentUser, profileOwner, getProfileInfo, isMine, params: { userId } }) => {
useEffect(() => {
getProfileInfo();
}, [userId]);
有点乱,我希望有比添加更多道具更好的方法来做到这一点,但它确实解决了问题。