也许我误解了一些东西,但是每次重新渲染发生时 useCallback Hook 都会运行。
我传递了输入 - 作为 useCallback 的第二个参数 - 不可更改的常量 - 但返回的记忆回调仍然在每次渲染时运行我的昂贵计算(我很确定 - 你可以在下面的代码片段中自己检查)。
我已将 useCallback 更改为 useMemo - useMemo 按预期工作 - 在传递的输入更改时运行。并真正记住昂贵的计算。
现场示例:
'use strict';
const { useState, useCallback, useMemo } = React;
const neverChange = 'I never change';
const oneSecond = 1000;
function App() {
const [second, setSecond] = useState(0);
// This expensive function executes everytime when render happens:
const calcCallback = useCallback(() => expensiveCalc('useCallback'), [neverChange]);
const computedCallback = calcCallback();
// This executes once
const computedMemo = …Run Code Online (Sandbox Code Playgroud)所以我有这段代码不能按预期工作。当前焦点是在父组件上使用 useState() 设置的,因此它是一个状态变量。但是,当父级中的 currentFocus 值发生变化时,这里的焦点变量本身不会更新。我本来希望重新渲染父组件,而重新渲染该组件会导致 foucs 值发生变化。
import React, { useRef, useEffect, useState } from 'react';
const CookieDetails = props => {
const {
name,
cost,
value,
numOwned,
onMouseClick,
cookieId,
currentFocus,
} = props;
let cookieInfoRef = useRef(null);
//My focus doesnt change even if I change currentFocus in parent component
const [focus, setFocus] = useState(currentFocus);
useEffect(() => {
console.log('currentFocus', currentFocus);
console.log('focus', focus);
console.log('cookieID', cookieId);
if (cookieInfoRef.current && cookieId === focus) {
console.log('current', cookieInfoRef.current);
cookieInfoRef.current.focus();
}
}, [focus]);
return (
<React.Fragment> …Run Code Online (Sandbox Code Playgroud) 因此,我正在尝试编写一段简单的(据说是!)代码,在用户键入时过滤数组中的字符串。
这是我所做的缩减版本。
简要解释一下,我有两个相互交互的组件。
FilterExample 其中包含要过滤的字符串列表MySearchBar它通过 prop 传递要过滤的字符串列表elementsToFilter。当搜索文本发生变化时,MySearchBar它会计算哪些索引elementsToFilter仍应显示并通过FilterExample回调将它们传递回onFilterTextChanged
我无法解释为什么在无限循环中出现以下错误,以及useEffect的依赖数组之一(即currentFilterIndices和fruits)将如何在每次渲染时发生变化
Warning: Maximum update depth exceeded. This can happen when a component calls
setState inside useEffect, but useEffect either doesn't have a dependency array,
or one of the dependencies changes on every render.
in FilterExample (at src/index.js:9)
in StrictMode (at src/index.js:8)
Run Code Online (Sandbox Code Playgroud)
import React, { useState, useEffect } from "react";
import MySearchBar from "./MySearchBar";
/** Basic example of …Run Code Online (Sandbox Code Playgroud) 我正在尝试执行以下操作的 react/react 钩子编写代码。
从父组件获取对象数组作为 prop 使用useState钩子将其设置为状态。根据预期的过滤器(时间和评级)对状态进行排序,并重新渲染子组件。我看到的是,下面的代码在排序后更新了状态,但是即使状态更新了,依赖于该状态的子组件也不会重新渲染。我认为子组件会在状态改变时自动重新渲染?
import React, {useState} from 'react';
import ProfilePostspreview from './ProfilePostspreview';
function ProfileNavigation(props){
const [newarray, setnewarray]=useState(props.parray); //'parray' object passed as props and saved as 'newarray' state
const otc = () => { //Function to sort the state by time and set a new state
let k=newarray;
setnewarray(k.sort((a, b) => (a.time > b.time) ? -1 : 1 ));
}
const orc = () => { //Function to sort the state by rating and then time …Run Code Online (Sandbox Code Playgroud) 我是 React 新手,想在我的项目中使用 react toast 通知官方文档,在他们的官方网站上,他们使用 react 钩子并使用它来执行通知,但我想在 componentWillMount 或 componentDidMount 的类组件中使用它。有什么办法可以做到这一点,或者我必须使用其他吐司组件。谢谢。
我想添加一个带有如下徽章的通知计数器: t-native
这是我的 MainTabScreen 代码
import React from 'react';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';
import Icon from 'react-native-vector-icons/Ionicons';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import Ionicons from 'react-native-vector-icons/Ionicons';
import IconBadge from 'react-native-icon-badge';
import {useTheme} from 'react-native-paper';
import { View } from 'react-native-animatable';
import {Text} from 'react-native';
import HomeScreen from '_screens/home';
import DetailsScreen from '_screens/details';
import ExploreScreen from '_screens/explore';
import ProfileScreen from '_screens/profile';
import EditProfileScreen from '_screens/editProfile';
import { UserNotification } from '_contexts/main';
const HomeStack = …Run Code Online (Sandbox Code Playgroud) 这段代码有什么区别:
<button onClick={()=>props.submitHandler(searchInputValue)}>Submit</button>
Run Code Online (Sandbox Code Playgroud)
和
<button onClick={props.submitHandler(searchInputValue)}>Submit</button>
Run Code Online (Sandbox Code Playgroud)
区别在于第一个有括号,第二个没有。没有括号,我的应用程序似乎无限期地重新渲染。有人可以向我解释一下吗?
一个很常见的 TypeScript 错误 TS2349,即sth has no call signatures.
在不同的情况下,它使用不同的变通方法来解决。但是处理反应的上下文,我发现的最佳解决方案是使用// @ts-ignore.
请问,在这种情况下正确的方法是什么?
// auth.tsx
import { CurrentUserContext } from 'components/currentUser';
import React, { useState, useEffect, useContext } from 'react';
const Auth = ({ onLogin }: {onLogin: any}) => {
const [, setCurrentUserState] = useContext(CurrentUserContext);
const [credentials, { data }] = useMutation(AUTH);
...
useEffect(() => {
if (data) {
// TypeScript Error without @ts-ignore:
// This expression is not callable.
// Type '{}' has no call signatures. TS2349 …Run Code Online (Sandbox Code Playgroud) 我想使用 React Hooks 添加千位分隔符的输入,但我不确定如何。到目前为止,我已经尝试了下面的代码,但没有奏效。
您能否指出可能是什么问题以及我该如何实施?
谢谢你。
const MainComponent = () => {
const [value, setValue] = useState(0);
const numberWithComma = () => {
return (+value).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
return (
<div>
<input
type="number"
onChange={numberWithComma}
placeholder="0"
/>
</div>
);
}
Run Code Online (Sandbox Code Playgroud) import React from "react";
function App() {
let time = new Date().toLocaleTimeString();
const [Time, setTime] = React.useState(time);
function getTime() {
time = new Date().toLocaleTimeString([], { hour12: false });
//console.log(time);
setTime(time);
}
setInterval(getTime, 2000);
return (
<div className="container">
<h1>{Time}</h1>
<button onClick={getTime}>Get Time</button>
</div>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud)
这是 React.js 的 App 组件。此代码正在创建一个运行时钟。当我注释掉 setInterval 函数时,console.log 工作正常,但是一旦我启用该功能,主屏幕上的所有内容都可以正常工作,但在控制台屏幕上,console.log(time) 正在运行无限次。请帮忙。感谢你。
react-hooks ×10
reactjs ×10
javascript ×6
use-state ×2
input ×1
react-native ×1
setinterval ×1
sorting ×1
typescript ×1
use-effect ×1