我正在尝试通过道具将对象传递给子组件。该值在useEffect挂钩中设置,并在传递给我的子组件时丢失。
我尝试在单独的函数中的useEffect钩子外部设置对象的值,但该值仍然丢失。
import React, { useState, useEffect } from 'react';
function SetValue(props){
let users = {};
useEffect(() => {
users = { user: 'bob' };
})
return <NewComponent users={users} />
}
export default SetValue;
Run Code Online (Sandbox Code Playgroud)
我期望props.users是{user:'bob'}而不是一个空对象{}。
错误消息是:
“每次渲染后,从React Hook内部对usesfffect的'users'变量的分配都将丢失。要随时间保留该值,请将其存储在useRef Hook中,并将可变值保留在'.current'属性中。否则,您可以在useEffect react-hooks / exhaustive-deps中直接移动此变量”
在卸载组件后设置状态时,React应记录以下错误:
Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
Run Code Online (Sandbox Code Playgroud)
但是,如果我返回一个空函数作为清理函数,它不会记录错误。
代码:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function Comp() {
const [state, setState] = useState("nothing");
useEffect(() => {
setState("loading");
sleep(1000).then(() => {
console.log("setting state");
setState("finished");
});
// When the below return exists it …Run Code Online (Sandbox Code Playgroud)