【问题标题】:React hooks - useEffect method keeps fetchingReact hooks - useEffect 方法不断获取
【发布时间】:2020-03-23 08:35:28
【问题描述】:

在我的许多组件中,我必须使用来自 store 的令牌来获取数据并表示它(页眉菜单、页脚菜单、页面上的产品、滑块图像等)。我要做的是仅在没有数据时才获取此数据,但是 React 每次令牌更改时都会继续发送请求(因为令牌是依赖项),即使我清楚地设置了条件并且如果我控制台我可以看到它.记录它。我做错了什么?

const [cities, setCities] = useState([]);

useEffect(() => {
 if (!cities.length) {
  fetch(`.....&token=${props.token}`)
  .then(response => response.json())
  .then(data => {

    if (data.data.results) {
    setCities(data.data.results.cities)

    }
   })
  }
}, [props.token, cities.length]);

【问题讨论】:

  • 由于每次重新渲染时都设置了citiescities 始终是一个新对象,因此cities.length 与前一个对象不同。此外,if(!cities.length) 始终为 true,因为始终定义了 cities,最初长度为 0,它仍然返回 true。你可以做的是if(cities.length<1)

标签: reactjs react-hooks use-effect


【解决方案1】:

cities 在第一次渲染时无论如何都会为空,因此您无需检查其长度并将其指定为依赖项:

const [cities, setCities] = useState([]);

useEffect(() => {
  fetch(`.....&token=${props.token}`)
    .then(response => response.json())
    .then(data => {
      if (data.data.results) {
        setCities(data.data.results.cities)
      }
    })
}, [props.token]);

您还可以记忆令牌以防止它触发useEffect回调:

const token = useMemo(() => props.token, []);

【讨论】:

    【解决方案2】:

    // 因评论而编辑

    // should be outside of the function
    let timesExecuted = 0
    
    function fetch () {
    useEffect(() => {
    if(props.token){
     timesExecuted = timesExecuted + 1
    }
    
    if (timesExecuted === 1) {
      fetch(`.....&token=${props.token}`)
      .then(response => response.json())
      .then(data => {
    
        if (data.data.results) {
        setCities(data.data.results.cities)
        }
       })
      }
    }, [props.token]);
    }
    

    所以它每次都会出现,但只有在 prop.token 是 OKEY 时才会执行(根据令牌验证随意修改第一个 IF)。

    【讨论】:

    • 这是为了确保令牌在那里,因为令牌也在其他组件中请求。
    • 每次代币变化时都需要获取城市吗?还是只需要 1 次?
    • 只有一次,但我不知道我的商店中是否已经有令牌,因为在安装应用程序时也会请求它。所以基本上我需要它作为依赖,所以当它存在时,我发送请求。
    • 完成,我根据您的需要编辑了我的答案,如果有效,请随时投票并标记为解决方案答案
    猜你喜欢
    • 2023-03-08
    • 2020-01-24
    • 1970-01-01
    • 2019-06-18
    • 2021-06-29
    • 2020-03-23
    • 2020-06-08
    • 2021-03-30
    • 1970-01-01
    相关资源
    最近更新 更多