【问题标题】:why console.log("hello) is printing six times in React hooks为什么 console.log("hello) 在 React hooks 中打印了六次
【发布时间】:2020-07-30 10:20:53
【问题描述】:

我正在学习反应钩子,我使用随机 API 来获取演示用户。谁能告诉我为什么 hello 被打印了 6 次,而且我无法在我的 return 语句中使用 if 语句

import React, {useState, useEffect} from "react";

function RandomUser () {
    const [users, setuser] = useState([]);
    const [loading, setLoading ] = useState(true);

    useEffect(()=>{
        console.log("fetching api ");
        fetch("https://randomuser.me/api/?results=50").then((res)=>{
            return res.json();
        }).then((res)=>{
            setuser(res.results);
            setLoading(false);
        })
    },[])
        console.log("hello");
    return (
        <>
        {loading && <h1>Loading</h1>}
        {users.map((v,i)=>{
            return(
                <li>
                    {v.name.first}
                </li>
            )
        })}
        </>
    );
}

export default RandomUser;

【问题讨论】:

    标签: reactjs react-native react-redux react-router react-hooks


    【解决方案1】:

    您的 console.log 行不在您的 useEffect 挂钩内,因此每次渲染都会被调用。 React 会在需要时调用 render,因此您不应在功能组件中包含具有副作用(钩子除外)的代码。 如果您希望在获得结果后调用该日志行,请将其移至 setLoading(false);

    之后

    JSX 不支持 JSX 字面量中的 if statements,但它确实支持三元表达式(condition ? trueValue : falseValue)和布尔表达式(condition &amp;&amp; trueValuecondition || falseValue),它们通常可以工作。或者,您可以将 if 块放在小的子组件或辅助函数中。只要确保你总是从每个代码分支返回一个组件或null。比如制作一个加载组件:

    function Loading ({loading=true}) {
      if (loading) return (<h1>Loading...</h1>)
      return null // notice the else is not necessary here
    }
    
    //and use it like this:
    
    return(<><Loading loading={loading} /></>)
    

    不支持 if 语句的原因是它们没有返回值(它们不是expressions),而三元和布尔表达式有。您可以从 if 语句内部调用 return,但这会导致整个函数返回,而不仅仅是 if 语句。

    JSX 被遵守React.createComponent(React.Fragment, null, children) 之类的东西。想象一下,如果你在 children 所在的位置添加 if 语句会发生什么。事实上,试试console.log(if (true) {true} else {false}) 之类的东西,看看会发生什么。它失败了,因为您必须提供一个 expression,而不是一个 statement 作为函数的参数。 (请注意,虽然通常表达式也是语句,但并非总是相反)。

    此视频可能对您有所帮助:https://en.hexlet.io/courses/intro_to_programming/lessons/expressions/theory_unit

    【讨论】:

    • 那么 if 语句呢,为什么会出错
    • 我回答了这两个问题:)。但是,关于 SO 的规则是一个问题,供将来参考。
    • 另外,您的第二个问题已经在这里提出并得到了回答:stackoverflow.com/questions/44046037/…
    猜你喜欢
    • 2020-02-21
    • 2020-02-03
    • 1970-01-01
    • 2021-09-18
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    相关资源
    最近更新 更多