我有一个看起来像这样的组件:
const MyComponent = props => {
const { checked, onChange, id } = props;
const [isChecked, setChecked] = useState(false);
useEffect(() => {
onChange && onChange({ isChecked: !!checked, id });
setChecked(checked);
}, [checked]);
const childProps = {
id,
isChecked
};
return <ChildComponent {...childProps} />;
};
Run Code Online (Sandbox Code Playgroud)
详尽的 deps lint 规则并不令人满意:
React Hook useEffect 缺少依赖项:
id和onChange. 包括它们或删除依赖项数组。(react-hooks/exhaustive-deps)eslint
我知道这一点id并且onChange不会改变,因此将它们添加到依赖项数组似乎没有必要。但规则不是警告,而是明确的指示去做某事。
是 ESLint 规则:
1)在这种情况下过于谨慎和有点愚蠢,所以可以忽略吗?
2) 突出最佳实践——即最大限度地减少将来可能发生的意外错误,例如,如果父组件的更改意味着 id将在将来的某个时候更改?
3) 显示当前代码的实际/可能问题?
我认为 useeffect 仅在渲染后调用一次,但它被多次执行,而不是按我预期的顺序执行。我希望它在提取过程中 msg 'data loading' ,然后一旦提取完成,呈现标题字段并警告“..Done...”一次,这应该是结束。我在两个点添加了 ALERT 和控制台日志来确定流程,并且警报和控制台日志都以不同的顺序出现不止一次。您能否运行此代码并查看行为。我将第二个参数数组保留为空以使其仅运行一次但无济于事。
其次,请澄清是否反应渲染意味着在屏幕上显示?LOAD 表示什么阶段?什么时候显示完成??
代码如下:
import React, { useEffect, useState } from "react";
//import "./App.css";
function DemoFetchZ() {
let data = { title: "Waiting for Data" };
const [todo, setTodo] = useState(data);
const [isData, setData] = useState(false);
const [isFetching, setFetching] = useState(false);
useEffect(() => { // called after the first render
async function fetchData() {
setFetching(true);
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos/1"
);
console.log("response = ", response);
let data = await response.json();
setTodo(data); …Run Code Online (Sandbox Code Playgroud) 这是我的useEffect一个简单的清理功能() => { inbox?.destroy(); },但是当我在那里使用清理功能时,它会发出警告。为什么会这样,清理函数不是合法的语法吗?如何修复它(当然不删除清理功能)?
useEffect(() => {
const { currentUser } = initialState!;
let inbox: Talk.Inbox;
if (!currentUser || !talkjsContainerRef.current) return;
Talk.ready.then(async () => {
const me = employeeToUser(currentUser);
window.talkSession = new Talk.Session({ appId, me });
if (id === undefined) {
// me without other => most recent message first
inbox = window.talkSession.createInbox();
} else {
// me with an other => select other
const other = employeeToUser(await readEmployee(Number(id)));
const conversation = window.talkSession.getOrCreateConversation(Talk.oneOnOneId(me, …Run Code Online (Sandbox Code Playgroud) 例如,如果我有组件 A 和 B,并且组件 B 是组件 A 的子级:
<A>
<B />
</A>
Run Code Online (Sandbox Code Playgroud)
在 A 中,我们有:
useEffect(() => {
console.log('Parent A useEffect')
})
Run Code Online (Sandbox Code Playgroud)
在 B 中,我们有:
useEffect(() => {
console.log('Child B useEffect')
})
Run Code Online (Sandbox Code Playgroud)
我做了一些测试,我看到了两件事:
父 A 使用效果
儿童B使用效果
儿童B使用效果
父 A 使用效果
在两种情况下,结果是相反的。这让我有点困惑。
我搜索了谷歌componentDidMount,我发现了这个:https : //github.com/facebook/react/blob/v15.0.1/docs/docs/ref-03-component-specs.md#mounting-componentdidmount
componentDidMount()子组件的方法先于父组件调用。
但我找不到有关的相应文档 useEffect
那么useEffect父/子组件中正确的执行顺序是什么?
为什么在将函数表达式传递到 useEffect 依赖项数组时会创建无限循环?函数表达式不会改变组件状态,它只是引用它。
// component has one prop called => sections
const markup = (count) => {
const stringCountCorrection = count + 1;
return (
// Some markup that references the sections prop
);
};
// Creates infinite loop
useEffect(() => {
if (sections.length) {
const sectionsWithMarkup = sections.map((section, index)=> markup(index));
setSectionBlocks(blocks => [...blocks, ...sectionsWithMarkup]);
} else {
setSectionBlocks(blocks => []);
}
}, [sections, markup]);
Run Code Online (Sandbox Code Playgroud)
如果标记改变了状态,我可以理解为什么它会创建一个无限循环,但它不是简单地引用部分属性。
对于那些正在寻找解决此问题的方法的人
const markup = useCallback((count) => {
const stringCountCorrection = count + 1;
return …Run Code Online (Sandbox Code Playgroud) 如果像这样的代码通过 的useEffect依赖关系重新渲染,
// ...
const Test = () => {
// ...
const value1 = "test1"
const func1 = () => {
// do something1
}
useEffect(() => {
const value2 = "test2"
const func2 = () => {
// do something2
}
}, [sth])
return (
// ...
)
}Run Code Online (Sandbox Code Playgroud)
value1&&&value2重新分配内存吗func1?func2
我很好奇,与优化有关。
我正在尝试测试App.jsx
import getUserInfo from './services/user';
const App = () => {
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState({
firstName: 'First Name',
lastName: 'Last Name',
});
useEffect(() => {
getUserInfo()
.then(({ Authorization: { FName, LName } }) => {
setUser({
firstName: FName,
lastName: LName,
});
setIsLoading(false);
})
.catch((error) => {
console.error(error);
setIsLoading(false);
});
}, []);
if (isLoading) {
return (<h1>Loading!</h1>)
} else {
return (<h1>Finished Loading!</h1>)
export default App
Run Code Online (Sandbox Code Playgroud)
和user.js
export default const getUserInfo = async …Run Code Online (Sandbox Code Playgroud) 我有使用钩子的函数组件。在useEffect钩子中,我只想从我的后端获取数据并将结果存储在 state 中。但是,尽管将数据变量添加为依赖项,但 useEffect 仍会在无限循环中触发 -即使数据没有更改。如何阻止 useEffect 连续触发?
我已经尝试了空数组 hack,它确实阻止了 useEffect 连续触发,但这不是所需的行为。例如,如果用户保存新数据,useEffect 应该再次触发以获取更新的数据 - 我不想模拟 componentDidMount。
const Invoices = () => {
const [invoiceData, setInvoiceData] = useState([]);
useEffect(() => {
const updateInvoiceData = async () => {
const results = await api.invoice.findData();
setInvoiceData(results);
};
updateInvoiceData();
}, [invoiceData]);
return (
<Table entries={invoiceData} />
);
};
Run Code Online (Sandbox Code Playgroud)
我希望 useEffect 在初始渲染后触发,并且仅在 invoiceData 更改时再次触发。
好吧:
useEffect(() => {
}, [props.lang]);
Run Code Online (Sandbox Code Playgroud)
每次使用 props.lang 更改时,我应该在 useEffect 内部做什么来重新渲染组件?
解决方案:
我通过改变一些问题的想法来解决这个问题(我使用另一个函数来很好地处理语言变化。
我正在尝试使用这样的 useEffect 函数:
const [data, setData] = useState({ courses: [] });
useEffect(async () => {
const result = await axios.get(
"http://example.com/api/v1/categories/"
);
await setData(result.data);
}, []);
console.log(data);
return (
<div>
<div>{data.info1}</div>
<div>{data.info2}</div>
<div>{data.info3}</div>
<div>{data.info4}</div>
</div>
);
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用data变量时,它有时会引发此错误:
TypeError: func.apply is not a function
HTMLUnknownElement.callCallback
C:/asdasd/node_modules/react-dom/cjs/react-dom.development.js:188
185 | window.event = windowEvent;
186 | }
187 |
> 188 | func.apply(context, funcArgs);
| ^ 189 | didError = false;
190 | } // Create a global error event handler. We …Run Code Online (Sandbox Code Playgroud) reactjs ×10
use-effect ×10
javascript ×4
react-hooks ×3
axios ×1
eslint ×1
fetch ×1
fetch-api ×1
jestjs ×1
redux ×1
rerender ×1
usecallback ×1