我正在尝试throttle在功能组件中使用lodash中的方法,例如:
const App = () => {
const [value, setValue] = useState(0)
useEffect(throttle(() => console.log(value), 1000), [value])
return (
<button onClick={() => setValue(value + 1)}>{value}</button>
)
}
Run Code Online (Sandbox Code Playgroud)
由于内部方法useEffect在每次渲染时都会重新声明,因此限制效果不起作用。
有没有人有一个简单的解决方案?
我知道您可以通过将数组作为可选的第二个参数传递来告诉React跳过效果。
例如:
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
Run Code Online (Sandbox Code Playgroud)
但是,如果我想控制比较怎么办?添加我自己的比较逻辑。
我希望React.memo可以将一个函数作为第二个参数传递给您。
我一直在学习/试验 React 钩子。当我在 Chrome 中使用 React DevTools 检查组件当前状态的值时,我看到状态很好,但实际的“字段”——即由各个useState钩子更新的状态变量——没有与它们相关的任何名称。相反,我看到的,例如,几个字符串,一对夫妇布尔值,等等。我一般都弄清楚是怎么回事,但是这似乎有问题-我希望能够看到其状态变量的名字是什么。
例如,如果我有类似的东西
const [doughnuts, setDoughnuts] = useState(24)
Run Code Online (Sandbox Code Playgroud)
当我查看 React DevTools 时,我希望看到类似“doughnuts: number : 24”的内容,而不仅仅是“number: 24”。
我是否错过了某处的一些设置,或者一些开启此功能的技巧?
我有一个带有用户名输入的表单,我正在尝试验证用户名是否在去抖动功能中使用。我遇到的问题是,当我输入“user”时,我的去抖动似乎不起作用,我的控制台看起来像
u
us
use
user
Run Code Online (Sandbox Code Playgroud)
这是我的去抖功能
export function debounce(func, wait, immediate) {
var timeout;
return () => {
var context = this, args = arguments;
var later = () => {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
Run Code Online (Sandbox Code Playgroud)
这是我在 React 组件中调用它的方式
import React, { useEffect } from 'react'
// verify username
useEffect(() => {
if(state.username !== "") {
verify();
}
}, [state.username]) …Run Code Online (Sandbox Code Playgroud) 在 React 文档的这个页面上:
https://reactjs.org/docs/faq-ajax.html
代码注释说...
注意:在这里处理错误而不是 catch() 块很重要,这样我们就不会吞下来自组件中实际错误的异常。
...关于在第二个参数.then之后处理错误fetch。文档中的完整片段是:
useEffect(() => {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
Run Code Online (Sandbox Code Playgroud)
它没有详细说明这个建议,我已经看到了许多使用 React 代码catch处理 API 调用错误的例子。我试过谷歌搜索,但找不到任何说明。
有人可以更详细地解释一下为什么我不应该catch用来处理fetch在useEffect钩子中进行API 调用时出现的错误吗?
还是在某些情况下可以这样做,而在其他情况下则不然?
“在组件中吞下异常 [...]”是什么意思? …
如果要限制useEffect仅在组件安装时运行,则可以添加useEffectwith的第二个参数[]。
useEffect(() => {
// ...
}, []);
Run Code Online (Sandbox Code Playgroud)
但是,如何使useEffect该组件仅在组件被更新(除了初始安装)的那一刻才运行?
在钩子的 React文档中,他们说:
“这还允许您使用效果内部的局部变量处理无序响应”
useEffect(() => {
let ignore = false;
async function fetchProduct() {
const response = await fetch('http://myapi/product/' + productId);
const json = await response.json();
if (!ignore) setProduct(json);
}
fetchProduct();
return () => { ignore = true };
}, [productId]);
Run Code Online (Sandbox Code Playgroud)
请通过解释帮助我更好地理解这一点:
return () => { ignore = true };谢谢!
I was trying to get the queries from my url pattern like localhost:3000/post?loc=100 by using useRouter() from "next/router" and fetching some data using that id from my server. It worked when I used it in a Stateless Functional Component.
But the page showing "Invalid hook call" then. I tried calling getInitalProps() of a Stateless Functional Component, but it didn't work there either and showed the same error.
Is there any rule to use this method?
I was developing a front-end …
我有一个场景,我需要检测组件的第一次渲染。我在这里构建了一个小例子。有人可以向我解释什么是正确的方法吗?
为什么大多数人建议使用 aref而不是普通状态。
https://codesandbox.io/s/condescending-burnell-0ex3x?file=/src/App.js
import React, { useState, useRef, useEffect } from "react";
import "./styles.css";
export default function App() {
const firstRender = useDetectFirstRender();
const [random, setRandom] = useState("123");
useEffect(() => {
if (firstRender) {
console.log("first");
} else {
console.log("second");
}
}, [random]);
return (
<div className="App">
<h1>Random Number is {random}</h1>
<button onClick={() => setRandom(Math.random())}>Change Name</button>
</div>
);
}
//Approach 1
// export function useDetectFirstRender() {
// const firstRender = useRef(true);
// useEffect(() => {
// firstRender.current = …Run Code Online (Sandbox Code Playgroud)实际上,我尝试验证表单并卡住以验证密码并确认密码。是否有任何属性useForm可以验证密码并在最新版本中以反应挂钩形式显示消息。请帮忙。实际上,我尝试验证表单并卡住以验证密码并确认密码。是否有任何属性useForm可以验证密码并在最新版本中以反应挂钩形式显示消息。请帮忙。
import React, { useState } from 'react'
import Image from '../../../Components/UI/Images/Image'
import SubmitButton from '../../../Components/UI/Button/Button'
import {useForm} from 'react-hook-form'
import illustrate from '../../../Assets/Imagesused/resetpass.png'
import '../Login/Login.css'
import "./CreatePass.css"
import "../ChangePassword/ChangePass.css"
const CreatePass = () => {
//show password
const [toggle1, setToggle1] = useState(false);
const [toggle2, setToggle2] = useState(false);
let password;
const { register, handleSubmit, formState: { errors }, reset,watch,getValues } = useForm({
mode: "onTouched"
});
password = watch("password", "");
const onSubmit = (data) => {
console.log(data); …Run Code Online (Sandbox Code Playgroud) react-hooks ×10
reactjs ×10
javascript ×2
debounce ×1
ecmascript-6 ×1
lodash ×1
next.js ×1
routing ×1
throttling ×1
use-effect ×1
use-ref ×1
validation ×1