首页 > 解决方案 > 我正在更改状态,但未呈现订阅的组件

问题描述

我找到元素的索引号,更改该索引中的值以免破坏数组中的顺序,将其作为新数组分派,但未呈现订阅的组件。

     var userPhotoIndex = userPhotos.findIndex(p => p.photoId === photoId) 
    
     if (userPhotoIndex > -1) {
        userPhotos[userPhotoIndex].likeCount -= 1;
        dispatch(getUserPhotosSuccess([...userPhotos]))
      }

实际上,redux 扩展中的状态会发生变化,但订阅的组件不会。

function LikeButton({ photo, photoId, setlikeCount }) {
const [isLike, setIsLike] = useState(false)
const dispatch = useDispatch()
const history = useHistory()
const isLogged = useSelector(state => state.isLoggedReducer);
const userPhotos = useSelector(state => state.userReducer.userPhotos);

const onClick = () => {
    var fd = new FormData();
    fd.append("photoId", photoId)
    if (!isLike) {
        axios.post(LIKE_API_URL, fd, { headers: authHeaderObj() }).then(() => {
            setIsLike(!isLike);
            setlikeCount(!isLike);
            var userPhotoIndex = userPhotos.findIndex(p => p.photoId === photoId)
            if (history.location.pathname.includes("me/" + profileFlowState.Likes)) {
                if (userPhotoIndex > -1) {
                    userPhotos[userPhotoIndex].likeCount += 1;
                    dispatch(getUserPhotosSuccess([...userPhotos]))
                }
            }

        }).catch(err => redirectErrPage(err, dispatch));
    }
    else {
        axios.delete(deleteLikePath(photoId), { headers: authHeaderObj() }).then(() => {
            setIsLike(!isLike);
            setlikeCount(!isLike);
            var userPhotoIndex = userPhotos.findIndex(p => p.photoId === photoId)
            if (history.location.pathname.includes("me/" + profileFlowState.Likes)) {
                if (userPhotoIndex > -1) {
                    userPhotos[userPhotoIndex].likeCount -= 1;
                    dispatch(getUserPhotosSuccess([...userPhotos]))
                }
            }
        }).catch(err => redirectErrPage(err, dispatch));
    }

}

useEffect(() => {
    if (isLogged) {
        axios.get(getIsLikePath(photoId), { headers: authHeaderObj() }).then(res => setIsLike(res.data))
    }
}, [isLogged, photoId])
if (!isLogged) {
    return <Button onClick={() => history.push("/login")} variant="outline-primary" style={{ borderRadius: 0 }} className="btn-sm">
        <i className="fa  fa-thumbs-up" style={{ fontSize: 16 }}></i>&nbsp;&nbsp;Beğen</Button>
}
return (
    <Button onClick={onClick} variant={isLike ? "primary" : "outline-primary"} style={{ borderRadius: 0 }} className="btn-sm">
        <i className="fa  fa-thumbs-up" style={{ fontSize: 16 }}></i>&nbsp;&nbsp;Beğen</Button>
)}

下面我正在渲染一个订阅的钩子。

订阅

function UserPhotos({ userId }) {
const dispatch = useDispatch();

const [isLoading, setIsLoading] = useState(true)
const setFalseIsLoading = () => setIsLoading(false);
useEffect(() => { dispatch(getUserPhotosApi(userId, setFalseIsLoading)); }, [userId, dispatch])

const userPhotos = useSelector(state => state.userReducer.userPhotos)

return <div className="mt-3">{isLoading ? <Loading /> : <div>
    <MapPhotoCard removeButton={true} refreshPhotos={(id) => {
        dispatch(getUserPhotosSuccess([...userPhotos.filter(p => p.photoId !== id)]))
    }} photos={userPhotos} /></div>}
</div>}

标签: javascriptarraysreactjsreduxreact-redux

解决方案


我想提一个重要的问题:

更改 redux 状态


在这种情况下,您有一个状态变量,即userPhotos驻留在 redux 存储中。userPhotos是数组类型的变量,改变likeCountvia 行userPhotos[userPhotoIndex].likeCount -= 1;是一种反模式。理想情况下,您希望首先使用以下两种方法之一克隆阵列:

使用拆分运算符

const userPhotosCopy = [...userPhotos]
userPhotosCopy[userPhotoIndex].likeCount -= 1
/*or userPhotosCopy.splice(userPhotoIndex, 1, {...userPhotosCopy[userPhotoIndex], likeCount: likeCount - 1 }]*/

使用 lodash

import _ from 'lodash'
const userPhotosCopy = _.cloneDeep(userPhotos)

获取 useEffect

在订阅组件中更新userPhotos, 后,理想情况下,您需要这样的模式:

const userPhotos = useSelector(state => state.userReducer.userPhotos);

return(
   // use userPhotos in whatever way you like
)

不确定该getUserPhotosSuccess操作在做什么,但似乎您没有userPhotos在订阅的组件中获取更新的对象


推荐阅读