在这个GitHub问题中,我基本上建议更改:
x = useCallback( ... , []);
Run Code Online (Sandbox Code Playgroud)
至:
x = useRef( ... ).current;
Run Code Online (Sandbox Code Playgroud)
两者相同,但是使用useRefReact不会比较依赖关系。
为此,有一个问题的答复:
有没有一种情况,没有依赖的useMemo或useCallback比useRef更好的选择?
我想不出一个,但我可能忽略了一些用例。
那么有人能想到这种情况吗?
鉴于这种
type LocationWeather = {
name: string;
temperature: number;
};
type IndexProp = {
savedLocationsWeather: LocationWeather[];
favoriteLocationWeather: LocationWeather;
};
function Index({ savedLocationsWeather, favoriteLocationWeather }: IndexProp)
Run Code Online (Sandbox Code Playgroud)
文档应该是什么样的?
我的第一个方法是:
/**
* Home page displaying weather details of saved locations and favorite location
* @param {object} props Component props
* @param {LocationWeather[]} props.savedLocationsWeather Weather details of saved locations
* @param {LocationWeather} props.favoriteLocationWeather Weather details of favorite location
* @return {TSX.Element}
*/
Run Code Online (Sandbox Code Playgroud)
但:
我不确定这是否是指定 savingLocationsWeather 的数组类型的正确方法,如
* @param {Array} props.savedLocationsWeather Weather details of saved …
document jsdoc typescript reactjs react-functional-component
在使用类组件时,总是建议不要使用内联匿名函数,因为它对性能不利,即
<input value{this.state.title}
onChange={(event) => this.setState({title: event.target.value})} />
Run Code Online (Sandbox Code Playgroud)
您通常必须在渲染方法之外创建一个名为 handleChange 的函数。这意味着每个渲染都不会创建一个新的内联匿名函数。
这让我想到了功能组件和 useState 等。
功能组件是渲染,所以如果我这样做
[title, setTitle] = useState()
<input value{this.title}
onChange={(event) => this.setTitle({title: event.target.value})} />
Run Code Online (Sandbox Code Playgroud)
这将与创建函数相同,因为无论如何都会在每次创建函数 - 在函数组件中
我知道可以使用 useCallback 钩子来缓存函数,但也建议不要过度使用它们,因为反应速度很快,并且使用 useCallback 实际上对于简单的情况可能很糟糕。
所以,这让我回到了我原来的问题。
在函数组件内部,我们应该使用内联匿名函数吗?考虑到在功能组件内创建一个函数无论如何都会被创建。
无论如何我认为两者都是垃圾收集
有人知道推荐的方法吗?
提前致谢
我正在将基于 jQuery 的项目转换为 React,并在功能组件中遇到引用问题:我有一个巨大的单词列表,每个单词都应该通过它们自己的引用进行访问,以便我可以根据用户的内容更改单独的类名正在打字(我可以使用一个巨大的状态对象来完成它,但性能会受到影响)。
如果我尝试访问引用的类列表,它是未定义的。现在我不确定 classList 在功能组件中通常不可用,或者 refs 是否未正确初始化:
const wordsRef = useRef([...Array(1000)].map(() => createRef()));
...
const displayWords = words.map((word, index) => (
<React.Fragment key={index}>
<span
ref={wordsRef.current[index]}
>
{word}
</span>{' '}
</React.Fragment>
));
...
useEffect(() => {
wordsRef.current[0].classList.add('highlight');
});
...
return (
<div className={classes.root}>
{displayWords}
</div>
);
Run Code Online (Sandbox Code Playgroud)
错误:无法读取未定义的属性“add”。
我只能找到 classList 的示例,但这可能不是在功能组件中添加/删除类的方法?
假设我有一个像这样的简单组件。
import React, { useState } from "react";
const Counter = () => {
const [counter, setCounter] = useState(0);
const incCounter = () => {
setCounter(counter + 1);
};
return (
<>
<p>Counter value is: {counter}</p>
<button className="increment" onClick={incCounter}>
Up
</button>
</>
);
};
export default Counter;Run Code Online (Sandbox Code Playgroud)
我想使用笑话和酶编写测试用例。但counter.instance()总是返回空值。任何帮助将不胜感激。
import React from "react";
import Counter from "../components/Counter";
import {
mount,
shallow
} from "./enzyme";
describe("Counter", () => {
let counter;
beforeEach(() => {
counter = shallow( < Counter / …Run Code Online (Sandbox Code Playgroud)我有一个带有 Formik 表单的有状态功能组件,它根据 isSubmitting 的值呈现不同的内容。
const MyPage: FunctionComponent<Props> = ({propOne, propTwo}) => {
<Formik ...>
...
{isSubmitting ? (
<div>show this on submitting</div>
) : (
<div>show this when not</div>
)}
</Formik>
};
Run Code Online (Sandbox Code Playgroud)
如何在我的测试中在 Formik 表单上设置 isSubmitting 的值?我希望能够在提交时测试页面的结构。
这是一种反模式吗?
export function Todo() {
...
const renderItem = (item) => (
item.done
? <strike>{item.text}</strike>
: <span>{item.text}</span>
);
return (
<ul>
{items.map((item) => <li>renderItems(item)</li>)}
</ul>
);
}
Run Code Online (Sandbox Code Playgroud)
与在 Todo 中创建 Item 组件相比,渲染这样的项目有什么区别,如下所示:
export function Todo() {
...
const Item = (props) => (
props.item.done
? <strike>{item.text}</strike>
: <span>{item.text}</span>
);
return (
<ul>
{items.map((item) => <li><Item item={item} /></li>)}
</ul>
);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
在本地创建被调用一次的组件/渲染函数怎么样?
export function SomeForm(props) {
const renderButton = (isComplete) => (
isComplete
? <button>Submit</button>
: <button disabled>Please complete</button>
); …Run Code Online (Sandbox Code Playgroud) 我有一个StatusContext这样命名的上下文:
export const statusCtxInit = {
open: false,
toggleOpen() {
this.open = !this.open;
}
};
const StatusContext = React.createContext(statusCtxInit);
export default StatusContext
Run Code Online (Sandbox Code Playgroud)
整个应用程序都与提供者一起包装:
// ...
<StatusContext.Provider value={statusCtxInit}>
// ...
Run Code Online (Sandbox Code Playgroud)
useContext为了使用我在 FC 中使用的上下文的值,当我获得该值时它就会起作用。
function MyComp() {
const status = useContext(StatusContext);
return (
<div>
{status.open
? `It's Open`
: `It's Closed`}
<button onClick={() => status.toggleOpen()}>
Toggle
</button>
</div>
)
}
export default MyComp
Run Code Online (Sandbox Code Playgroud)
另一方面,我也想通过调用来更改上下文toggleOpen,但是它不能按我想要的方式工作。实际上该值发生变化但不影响MyComp.
我做错了什么?我该怎么办?
如果我想在第一次渲染组件后调用 API,我知道我们有useEffect钩子来调用 API 方法。(我只讨论功能组件。没有类组件)。
有什么办法,我可以在我的组件第一次渲染之前调用 API。
这个问题的原因是,如果某些 UI 部分依赖于 API,我不想在第一次渲染时向用户显示任何不完整的信息,一旦我从 API 获取数据,这些信息就会改变。这似乎是一个糟糕的 UI 体验。
编辑:我得到了一些使用 useLayoutEffect 或任何消耗性标志来检查它是否渲染的建议。我已经检查过 useLayoutEffect 不起作用,并且通过使用 consumable 标志,我们只是增加了复杂性。
对此我们有没有更好的办法呢?
javascript reactjs react-lifecycle react-hooks react-functional-component
考虑 React 中这个简单的 TextField 组件:
import React, { useState } from "react";
import { TextField, Grid } from "@mui/material";
const handleEnter = (event) => {
console.log("In handleEnter");
if (event.key == "Enter" && event.shiftKey) {
console.log("Detected Shift+Enter key");
} else if (event.key == "Enter") {
console.log("Detected Enter key");
}
};
export default function Example() {
const [value, setValue] = React.useState("");
const handleChatBoxChange = (event) => {
setValue(event.target.value);
};
return (
<Grid container>
<TextField
id='chatBox'
maxRows={90}
onKeyDown={handleEnter}
value={value}
onChange={handleChatBoxChange}
variant='filled'
></TextField>
</Grid> …Run Code Online (Sandbox Code Playgroud) javascript event-handling node.js reactjs react-functional-component
react-functional-component ×10
reactjs ×10
react-hooks ×4
javascript ×3
typescript ×2
document ×1
enzyme ×1
formik ×1
jestjs ×1
jsdoc ×1
jsx ×1
node.js ×1
ref ×1