[英]Why are some imported React-Native Redux actions changing values and triggering onEffects multiple times?
Here is my setup:这是我的设置:
// store/actions/user.js
export const discoverFollowingStatus = followsId => {
return (dispatch, getState) => {
const userId = getState().user.user.id;
findFollowingFromTo(userId, followsId).then(following => {
dispatch({
type: UPDATE_FOLLOWING_STATUS,
payload: {
followsId,
following: following !== null,
},
});
});
};
};
// component.js
import {
discoverFollowingStatus,
} from '../store/actions/user';
...
useEffect(() => {
discoverFollowingStatus(followedUserId);
console.log(discoverFollowingStatus);
}, [followedUserId, discoverFollowingStatus]);
The console is printing lots of functions that aren't grouping together:控制台正在打印许多未组合在一起的功能:
The big problem is that the screen is constantly re-rendering because the useEffect is triggering.最大的问题是屏幕不断地重新渲染,因为 useEffect 正在触发。 Why would that imported constant change and trigger it?为什么导入的常量会改变并触发它?
The issue here is that you have two objects/values inside []
at the end of your useEffect.这里的问题是在 useEffect 末尾的[]
中有两个对象/值。 This should fix it if you want to keep watching those two values.如果您想继续观察这两个值,这应该可以解决它。
import { discoverFollowingStatus, } from '../store/actions/user'; ... useEffect(() => { if(followedUserId && discoverFollowingStatus){ discoverFollowingStatus(followedUserId); console.log(discoverFollowingStatus); } }, [followedUserId, discoverFollowingStatus]);
Note here that discoverFollowingStatus
will only be triggered if both discoverFollowingStatus
and followedUserId
are defined this time.这里注意, discoverFollowingStatus
如果双方才会触发discoverFollowingStatus
和followedUserId
定义这个时候。
Otherwise it is recommended in the documentation to split your useEffect for separation of concerns.否则建议在文档中拆分 useEffect 以分离关注点。 You should be using a useEffect to set a state when followedUserId
is defined and safe to use by discoverFollowingStatus
你应该使用useEffect设置状态时followedUserId
被定义,使用安全discoverFollowingStatus
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.