简体   繁体   English

使用 react useState 和 useEffect 时的未知行为

[英]Unknown behavior when using react useState and useEffect

I have this code:我有这个代码:

function Parent(props) {

    const [items, setItems] = useState([]);
    const [itemArr, setItemArr] = useState([]);
    const [reRender, setReRender] = useState(false);

    useEffect(() => {
        let _items = items.slice(0).reverse().map((item, idx) => {
            return {
                type: {
                    subject: item.type,
                    type: "text"
                },
                child: {
                    subject: <Child
                                data = {item}
                             ></Child>,
                    type: "inline"
                },
            }
        });

        setItemArr(_items);
    }, [reRender])

    function newItem(info) {

        let [date, time] = getDate();

        let tmp = items;
        tmp.push({
            id: items.length,
            type: info.type,
            date: date,
            time: time
        });
        
        setItems(tmp);
        setReRender(!reRender);
    }

    return (
            <MyTable
                 items = {itemArr}
            ></MyTable>
    )
}

and my Child component:和我的Child组件:


export default function ScanTimer(props) {

    console.log(props.data);

    useEffect(() => {
        console.log(props.data);
    }, []);

    return(
        <div></div>
    )
}

when I run my app, and add two item to the table, first console.log in child component (the one that is out of useEffect ) shows right data.当我运行我的应用程序并向表中添加两个项目时,子组件中的第一个console.log (不在useEffect的那个)显示正确的数据。 but last one (in useEffect ) shows wrong data (the data that is for first item inserted into table).但最后一个(在useEffect中)显示错误的数据(插入到表中的第一个项目的数据)。

it happens also when I init a state In this way:当我以这种方式初始化 state 时也会发生这种情况:

const [data, setData] = useState(props.data);

in the Child element.在子元素中。

I don't know why it happens.我不知道为什么会这样。 can somebody help me??有人可以帮助我吗?

first console.log in child component (the one that is out of useEffect) shows right data子组件中的第一个console.log(不在useEffect中的那个)显示正确的数据

That runs every time the component is rendered.每次渲染组件时都会运行。 It will always show the latest data.它将始终显示最新数据。

but last one (in useEffect) shows wrong data (the data that is for first item inserted into table但最后一个(在useEffect中)显示错误的数据(插入到表中的第一个项目的数据

The runs every time the dependency list changes.每次依赖关系列表更改时运行。

So it runs on the first render (with the first value) because the dependencies have changed from "didn't exist" to "exists".所以它在第一个渲染(第一个值)上运行,因为依赖关系已经从“不存在”变为“存在”。

Then on subsequent renders, since there are no dependancies in the list (you passed an empty array), they haven't changed, so it doesn't run.然后在随后的渲染中,由于列表中没有依赖项(您传递了一个空数组),它们没有改变,所以它不会运行。

That is the point of useEffect .这就是useEffect的意义所在

If you want it to run when the data changes, you have to include that in the dependency list.如果您希望它在数据更改时运行,则必须将其包含在依赖项列表中。

useEffect(() => {
    console.log(props.data);
}, [props.data]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React:使用 useEffect 和/或 useState 钩子混淆行为 - React: Confusing behavior with useEffect and/or useState hooks 使用 useEffect 将 react 查询 state 移动到 useState - Using useEffect to move react query state to useState 在 useEffect 中使用 useState 时,Map 不是函数 - Map is not a function when using useState in useEffect React useState &amp; useEffect 混淆 - React useState & useEffect confusion 在 React 中使用 useState() 和 useEffect() 时设置来自 axios 的 state 值 - Setting state value coming from axios when using useState() and useEffect() in React 当 state 发生变化时做出反应,useState 和 useEffect 是否也更新了? - In react when state changes, are useState and useEffect also updated? 使用 React 更新二维数组并挂钩 useState 和 useEffect - Update 2d array using React and hooks useState and useEffect 点击两次查看值 - UseState - UseEffect React using Function Component - Clicking twice to see the value - UseState - UseEffect React using Function Component Javascript - 使用“useEffect()”和“useState”未定义来自异步获取的反应数据 - Javascript - React Data from Async fetching is undefined using 'useEffect()' and 'useState' 使用 React 中的 useEffect 和 useState 钩子从获取请求中管理数组 - Manage array from get request using useEffect and useState hooks in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM