Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 页面加载时,React Follow功能激活_Reactjs_Rails Api - Fatal编程技术网

Reactjs 页面加载时,React Follow功能激活

Reactjs 页面加载时,React Follow功能激活,reactjs,rails-api,Reactjs,Rails Api,我正在尝试在react rails api web应用程序中实现follow/unfollow函数。当前,当我单击follow/unfollow按钮时,follow和unfollow post/delete很好 但是,每当用户访问另一个用户页面时,当页面加载时,它将跟随/取消跟随,而无需单击“跟随/取消跟随”按钮。我不明白为什么会发生这种情况,因为对于我的post/delete,当我的follow/unfollow状态更改时,useEffect second参数设置为关闭 请帮我弄清楚为什么会发

我正在尝试在react rails api web应用程序中实现follow/unfollow函数。当前,当我单击follow/unfollow按钮时,follow和unfollow post/delete很好

但是,每当用户访问另一个用户页面时,当页面加载时,它将跟随/取消跟随,而无需单击“跟随/取消跟随”按钮。我不明白为什么会发生这种情况,因为对于我的post/delete,当我的follow/unfollow状态更改时,useEffect second参数设置为关闭

请帮我弄清楚为什么会发生这种情况以及如何预防。如果需要更多信息,请告诉我

import React, {useState, useEffect} from 'react'
import {Link, useParams} from 'react-router-dom'
import decode from 'jwt-decode'
function NotUserPage() {
    const {id} = useParams()
    const [user, setUser] = useState({})
    const loggedUser = decode(localStorage.getItem("token"))
    const username = loggedUser.username
    const userId = loggedUser.user_id 
    const [followUnFollow, setFollowUnFollow] = useState("true")
   
  
    const toggleFollowUnFollow = () => {
        setFollowUnFollow(!followUnFollow)
    }
    

    const fetchUserData = () => {
        fetch(`http://localhost:3000/users/${id}`)
            .then(res => res.json())
            .then(data => setUser(data))
    }

    useEffect(() => {
        fetchUserData()
    }, [])


    const unFollow = () => {
        fetch(`http://localhost:3000/users/${id}/unfollow`, {
            method: "POST",
            body:  JSON.stringify({
                follower_id: userId,
                followee_id: id
            }),
            headers: {
                "Content-type": "application/json",
                "Authorization": `bearer ${localStorage.getItem("token")}`,
              },
            
            })
            .then(res => res.json())
            .then(data => console.log(data))
                
    }
  
    useEffect(() => {
        unFollow()
    }, [followUnFollow])
   

 


    const handleFollow = () => {
        fetch(`http://localhost:3000/users/${id}/follow`, {
            method: "POST",
            body:  JSON.stringify({
                follower_id: userId,
                followee_id: id
            }),
            headers: {
                "Content-type": "application/json",
                "Authorization": `bearer ${localStorage.getItem("token")}`,
              },
            
            })
            .then(res => res.json())
            .then(data => console.log(data))
                
    }
    useEffect(() => {
        handleFollow()
    }, [followUnFollow])
  
    const fButton = () => {
       
        toggleFollowUnFollow() ? handleFollow() : unFollow()

    }

    return (
        <div>
           {user.username} 
           <button onClick={fButton}>follow</button>
        </div>
    )
}

export default NotUserPage

import React,{useState,useffect}来自“React”
从“react router dom”导入{Link,useParams}
从“jwt解码”导入解码
函数NotUserPage(){
const{id}=useParams()
const[user,setUser]=useState({})
const loggedUser=decode(localStorage.getItem(“令牌”))
const username=loggedUser.username
const userId=loggedUser.user\u id
const[followUnFollow,setFollowUnFollow]=useState(“true”)
const toggleFollowUnFollow=()=>{
setFollowUnFollow(!followUnFollow)
}
const fetchUserData=()=>{
取回(`http://localhost:3000/users/${id}`)
.then(res=>res.json())
.然后(数据=>setUser(数据))
}
useffect(()=>{
fetchUserData()
}, [])
const unFollow=()=>{
取回(`http://localhost:3000/users/${id}/unfollow`{
方法:“张贴”,
正文:JSON.stringify({
follower_id:userId,
followee_id:id
}),
标题:{
“内容类型”:“应用程序/json”,
“授权”:`bearer${localStorage.getItem(“令牌”)}`,
},
})
.then(res=>res.json())
.then(数据=>console.log(数据))
}
useffect(()=>{
展开()
},[followUnFollow])
const handleFollow=()=>{
取回(`http://localhost:3000/users/${id}/follow`{
方法:“张贴”,
正文:JSON.stringify({
follower_id:userId,
followee_id:id
}),
标题:{
“内容类型”:“应用程序/json”,
“授权”:`bearer${localStorage.getItem(“令牌”)}`,
},
})
.then(res=>res.json())
.then(数据=>console.log(数据))
}
useffect(()=>{
handleFollow()
},[followUnFollow])
常量fButton=()=>{
toggleFollowUnFollow()?handleFollow():unFollow()
}
返回(
{user.username}
跟随
)
}
导出默认NotUserPage
从“React”导入React,{useState,useffect}
从“react router dom”导入{Link,useParams}
从“jwt解码”导入解码
函数NotUserPage(){
const{id}=useParams()
const[user,setUser]=useState({})
const loggedUser=decode(localStorage.getItem(“令牌”))
const username=loggedUser.username
const userId=loggedUser.user\u id
const[following,setFollowing]=useState(false)
const fetchUserData=()=>{
取回(`http://localhost:3000/users/${id}`)
.then(res=>res.json())
.然后(数据=>setUser(数据))
}
useffect(()=>{
fetchUserData()
}, [])
const unFollow=()=>{
取回(`http://localhost:3000/users/${id}/unfollow`{
方法:“张贴”,
正文:JSON.stringify({
follower_id:userId,
followee_id:id
}),
标题:{
“内容类型”:“应用程序/json”,
“授权”:`bearer${localStorage.getItem(“令牌”)}`,
},
})
.then(res=>res.json())
.then(数据=>console.log(数据))
.然后(()=>setFollowing(false))
}
const handleFollow=()=>{
取回(`http://localhost:3000/users/${id}/follow`{
方法:“张贴”,
正文:JSON.stringify({
follower_id:userId,
followee_id:id
}),
标题:{
“内容类型”:“应用程序/json”,
“授权”:`bearer${localStorage.getItem(“令牌”)}`,
},
})
.then(res=>res.json())
.then(数据=>console.log(数据))
.然后(()=>setFollowing(true))
}
常量fButton=()=>下面的?unFollow():handleFollow();
返回(
{user.username}
跟随
)
}
导出默认NotUserPage

无论依赖关系如何,组件加载时始终运行useEffect。为了防止这种情况,在useEffect的第一行放一个if语句,useEffect将运行,但如果条件不是metThank@Aleks,它将短路/提前退出。它现在正在按预期工作。我的理解是,使用if语句,它现在可以作为ComponentDidUpdate正常工作?取决于if语句,如果您阻止像这样的第一次渲染
让k=0如果(k==0){k++;return;}
inside useffect,那么是。在您的情况下,我只需将followUnFollow默认值设置为undefined,并在if语句中检查它。另外,您真的不需要两个钩子,我将添加编辑过的代码作为答案谢谢您的帮助@Aleks。当我尝试编写代码片段并单击“跟随”按钮时,它会将状态设置为false,并且不会在true/false之间交替。我尝试使用一个带有if语句的单一useffect来确定follow或unFollow是否会运行,得到了相同的结果。如有可能,请告知。是否更改此
const fButton=()=>以下内容?handleFollow():unFollow()
常数fB
import React, {useState, useEffect} from 'react'
import {Link, useParams} from 'react-router-dom'
import decode from 'jwt-decode'
function NotUserPage() {
    const {id} = useParams()
    const [user, setUser] = useState({})
    const loggedUser = decode(localStorage.getItem("token"))
    const username = loggedUser.username
    const userId = loggedUser.user_id 
    const [following, setFollowing] = useState(false)
  
    const fetchUserData = () => {
        fetch(`http://localhost:3000/users/${id}`)
            .then(res => res.json())
            .then(data => setUser(data))
    }

    useEffect(() => {
        fetchUserData()
    }, [])

    const unFollow = () => {
        fetch(`http://localhost:3000/users/${id}/unfollow`, {
            method: "POST",
            body:  JSON.stringify({
                follower_id: userId,
                followee_id: id
            }),
            headers: {
                "Content-type": "application/json",
                "Authorization": `bearer ${localStorage.getItem("token")}`,
              },
            
            })
            .then(res => res.json())
            .then(data => console.log(data))
            .then(() => setFollowing(false))
                
    }
 
    const handleFollow = () => {
        fetch(`http://localhost:3000/users/${id}/follow`, {
            method: "POST",
            body:  JSON.stringify({
                follower_id: userId,
                followee_id: id
            }),
            headers: {
                "Content-type": "application/json",
                "Authorization": `bearer ${localStorage.getItem("token")}`,
              },
            
            })
            .then(res => res.json())
            .then(data => console.log(data))
            .then(() => setFollowing(true))
                
    }
  
    const fButton = () => following ? unFollow() : handleFollow();


    return (
        <div>
           {user.username} 
           <button onClick={fButton}>follow</button>
        </div>
    )
}

export default NotUserPage