[英]functions props change doesn't occurs child component render why?
I have App, TseTest(which has msg props) components and TseTest have variables a, b and each values have random number and it prints values on console.我有 App、TseTest(有 msg 道具)组件,TseTest 有变量 a、b,每个值都有随机数,它会在控制台上打印值。
When I press button then msg state in App will change function () {console.log("t");}
to function () {console.log("tt");}
当我按下按钮时,应用程序中的 msg state 会将
function () {console.log("t");}
更改为function () {console.log("tt");}
And I expected TesTest will rerender due to msg is changed and prins a,b on console with new values but it's not.而且我预计 TesTest 将重新渲染,因为 msg 已更改并在控制台上使用新值打印 a,b 但事实并非如此。
It seems props of function type is not occurs render when it changes.似乎 function 类型的道具在更改时不会出现渲染。
Do you know why?你知道为什么吗?
const TseTest = ({ msg }) => {
const a = Math.random();
const b = () => Math.random();
useEffect(() => {
// console.log(msg)
msg && msg();
}, [msg]);
return (
<>
{console.log("a", a)}
{console.log("b", b())}
</>
);
};
const App = () => {
const [msg, setMsg] = useState(function () {
console.log("t");
});
return (
<>
<button
onClick={() => {
setMsg(function () {
console.log("tt");
});
}}
>
test
</button>
<TseTest msg={msg} />
</>
);
};
export default App;
expected预期的
t
a 0.9264919874929558
b 0.5546484347625045
tt
a 0.232132412412...
b 0.6546456...
results结果
t
a 0.9264919874929558
b 0.5546484347625045
tt
https://codesandbox.io/embed/tender-maxwell-vbtk2?fontsize=14&hidenavigation=1&theme=dark https://codesandbox.io/embed/tender-maxwell-vbtk2?fontsize=14&hidenavigation=1&theme=dark
useState
takes a function
which is actually used for lazy initialization of state ie for the first time whatever is returned from this function will be set to initial state. useState
takes a function
which is actually used for lazy initialization of state ie for the first time whatever is returned from this function will be set to initial state.
const [msg, setMsg] = useState(function () {
console.log("t");
});
Now you were expecting msg
to be set as function
but what's happening is that the returned value from that function
is being set and which in your case is undefined
since you're not returning anything.现在您期望将
msg
设置为function
但正在发生的事情是来自该function
的返回值正在设置,并且在您的情况下是undefined
的,因为您没有返回任何内容。
Similarly, setMsg
also takes a function
as it's first parameter which allows access to the previous state
in it's argument and whatever you return from it is set to msg
同样,
setMsg
也采用function
作为它的第一个参数,它允许访问它的参数中的previous state
并且从它返回的任何内容都设置为msg
setMsg(function () {
console.log("tt");
});
So in above since you're not returning anything, undefined
is returned.所以在上面,因为你没有返回任何东西,所以
undefined
被返回。
So there is no difference in value of msg
as both times it is undefined
, thus no re-render.所以
msg
的值没有区别,因为它两次都是undefined
,因此没有重新渲染。
Here is a forked sandbox which achieves what you want:-这是一个分叉的沙箱,可以实现您想要的:-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.