我正在阅读 React 中的钩子,但在理解 useRef 和 useCallback 钩子之间的区别时遇到了一些麻烦。
具体来说,我希望了解如何使用这两个来避免对子组件进行不必要的重新渲染。
根据我对 stack overflow 上的这个答案的理解,以下函数可以写为:
const Avatar = function({ history, url, fullName }) {
const onMenuItemClick = urlToNavigate => history.push(urlToNavigate),
onMenuItemClickRef = useRef(onMenuItemClick);
return (
<Menu
label={<RoundedImage src={url} alt={fullName} />}
items={[
{ label: `Logged in as: ${fullName}` },
{
label: "Liked articles",
onClick: () => onMenuItemClickRef.current("/liked-articles")
},
{
label: "Edit profile",
onClick: () => onMenuItemClickRef.current("/profile")
},
{ label: "Logout", onClick: () => console.log("Logging out") }
]}
/>
);
}; …
Run Code Online (Sandbox Code Playgroud) 我已经弹出了反应脚本,并且我的 setupProxy.js 中有以下内容。
module.exports = function(app) {
app.use(
proxy({
changeOrigin: true,
logLevel: "debug",
onProxyReq: function onProxyReq(proxyReq, req, res) {
console.log(
chalk.red(
'Request'
)
);
},
onError(err, req, res) {
console.log(err);
},
secure: false,
target: "http://www.google.com"
})
Run Code Online (Sandbox Code Playgroud)
我希望上面的内容能够代理,并记录从反应应用程序发出的每个请求,但事实并非如此。我需要在 Webpack 中添加配置吗?谢谢
我正在考虑将当前babel.config.js
文件转换为babel.config.mjs
文件。这应该很简单,但由于某种原因,当我尝试api
在配置中使用函数参数时,我收到以下错误:
评估完成后无法更改缓存。
这是我的配置,非常简单:
export default function(api) {
api.cache(true) // if I remove this then it will work
return {
plugins,
presets
};
}
Run Code Online (Sandbox Code Playgroud) 我正在使用useEffect挂钩,在某些情况下,我不需要返回任何东西。处理这种情况的最佳方法是什么?
// fooRef is a reference to a textfield (belonging to the same component). Sometimes the fooRef is not there,because of redirections) that's why I need to check if it exists
useEffect(() => fooRef.current && fooRef.current.focus() , [fooRef])
Run Code Online (Sandbox Code Playgroud)
当以这种方式使用它时,React会抱怨以下错误消息: 效果函数除用于清理的函数外,不得返回任何其他内容。您返回了null。如果您的效果不需要清理,则返回undefined(或不返回)。
最好的选择是返回未定义或空函数吗?