[英]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.