我想显示一个与对象属性相关的 div,该属性为 true 或 false。我使用了一种方法,但我不确定这是最好的方法,或者它是否会带来性能问题。
我正在循环中检查返回部分的属性,以避免额外的数组操作。但我认为这会导致额外的渲染。
另一个选项是从返回部分外部检查该属性。但这会导致额外的数组操作。
哪种方式最适合我?我在下面展示了两种不同的实现。
选项1:
const RadioButtonList: FunctionComponent<RadioButtonListProps> = ({ items, changeFilter }) => {
const [showClearIcon, setShowClearIcon] = React.useState(false);
return (
<div className="radio-button-list">
{showClearIcon && <div className="clear-icon">clear</div>}
<ul>
{items.map(item => {
/* this is the area what I'm checking the property */
if (item.selected) {
setShowClearIcon(true);
}
return (
<li key={item.id}>
<label htmlFor={item.text} className="radio">
<span className="input">
<input type="radio" onClick={changeFilter} readOnly />
</span>
</label>
</li>
);
})}
</ul>
</div>
);
};
Run Code Online (Sandbox Code Playgroud)
选项2:
const RadioButtonList: FunctionComponent<RadioButtonListProps> = …Run Code Online (Sandbox Code Playgroud) 我的组件中有三个不同的状态变量。其中两个状态连接到范围滑块,当我移动滑块时更新状态。一是为了成本,一是为了时间。
我的问题是,如何根据前两个状态的信息更新第三个状态?
function Calculator() {
const [loanAmount, setLoanAmount] = useState(100000);
const [loanTime, setLoanTime] = useState(5);
const calculateCost = () => {
const totalMonths = loanTime * 12;
const monthlyFee = 0.00825;
const monthlyFeePlusOne = 1.00825
const totalPrice =
(loanAmount*0.00825)*(Math.pow((1+0.00825), 60))/(Math.pow((1+0.00825), 60)-1);
return Math.round(totalPrice);
};
const [calculation, setCalculation] = useState(calculateCost());
<input
className="slider"
type="range"
min="20000"
max="200000"
value={loanAmount}
step="10000"
onChange={(e) => setLoanAmount(e.target.value)}
/>
<label>{loanAmount}</label>
<input
className="slider"
type="range"
min="2"
max="10"
value={loanTime}
step="1"
onChange={(e) => setLoanTime(e.target.value)}
setCalculation
/>
<label> {calculation} </label>
Run Code Online (Sandbox Code Playgroud) 以下是使用useState(). 除了+单击按钮时,它工作正常,然后数字可以在某些数字之间交替7001并7000快速闪烁。
实际上,不点击+,数字表现良好,但最多可达 8000 或 9000,然后它可能会开始在某些数字之间闪烁。为什么会这样,如何修复?
PS最初的调试发现是:它似乎Counter()被多次调用,每次都设置一个间隔计时器。所以“神奇地”,似乎useState()只运行了一次——出于某种未知和神奇的原因——或者它运行了不止一次,但每次都返回完全相同的内容,对于某种神奇的机制。0真的是第一次这样的初始值。当它useState(0)用于未来时,它count不是0......我们不希望那样,但它也不是那么实用(就像在数学函数中一样)。
function Counter() {
const [count, setCount] = React.useState(0);
setInterval(() => {
setCount(count + 1000);
}, 1000);
return (
<div>
<button onClick={() => setCount(count + 1)}> + </button>
{ count }
<button onClick={() => setCount(count - 1)}> - </button>
</div>
);
}
ReactDOM.render(<Counter />, document.querySelector("#root"));Run Code Online (Sandbox Code Playgroud)
button { margin: 0 1em } …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) 为什么会fetchData多次触发?在console.log似乎环几乎是无限?如何让它在加载时仅运行一次并在fetchData()稍后调用时仅触发一次?我在这里做错了什么或错过了什么?
const [data, setData] = useState(null);
let fetchData = React.useCallback(async () => {
const result = await fetch(`api/data/get`);
const body = await result.json();
setData(body);
console.log(data)
},[data])
useEffect(() => {
fetchData();
},[fetchData]);
Run Code Online (Sandbox Code Playgroud)
更新(附加问题):如何在下面data的之前等待填充return()现在给出错误,因为它最初为空?:data.map is not a function
return (
<select>
{data.map((value, index) => {
return <option key={index}>{value}</option>
})}
</select>
)
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) 正在运行无限次。请帮忙。感谢你。
我必须显示三个组件(卡),用户可以从中选择一个。我将这三个组件放置在 a 中ScrollView:
...
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
<LocationAndPriceCard
price={'100'}
title={'Choice 3'} />
<LocationAndPriceCard
price={'200'}
title={'Choice 2'} />
<LocationAndPriceCard
price={'300'}
title={'Choice 1'}} />
</ScrollView>
...
Run Code Online (Sandbox Code Playgroud)
以下是LocationAndPriceCard编码方式:
...
function LocationAndPriceCard({ price, title }) {
const [selectedLocation, setSelectedLocation] = useState("red")
const styles = getStyles(selectedLocation);
const selected = () => {
if (selectedLocation == "red") {
setSelectedLocation("green")
} else {
setSelectedLocation("red")
}
}
return (
<TouchableOpacity style={styles.frame} onPress={selected}>
<Text style={styles.priceTxt}>RM {price}</Text>
<Text style={styles.title} numberOfLines={2}>{title}</Text>
</TouchableOpacity>
);
}
const getStyles = …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个简单的闲置游戏,以便我可以更深入地研究网络开发。然而,React 抱怨重新渲染次数太多,但我确实想每秒重新渲染一次。
这是我目前拥有的代码。
> const Game = () => { const [resourceCopper, setResourceCopper] =
> useState(0);
>
> const gatherCopper = () => {
> setResourceCopper(resourceCopper + 1); };
>
> setInterval(gatherCopper(), 1000);
>
> return (
> <section className="main-window-container">
> <section className="left-container">
> <h3>Resources:</h3>
> <p>Copper: {resourceCopper}</p>
> </section>
Run Code Online (Sandbox Code Playgroud) 我有从 redux 中提取的事件,如果events数组包含数据,updateData则将用于将事件过滤到状态 var 中data。
我已经data和events都添加到了这里提到的依赖数组中。但我仍然收到此错误:
const SingleTable = () => {
const events = useSelector(state => eventsSelector(state));
const [data, updateData] = useState([]);
const [sortCol, updateSortCol] = useState(0);
const [sortDir, updateSortDir] = useState('ascending');
useEffect(() => {
const formattedArray = events ? formatLoss(events): [];
events && updateData(formattedArray);
}, [data, events]);
//...
Run Code Online (Sandbox Code Playgroud)
想法,想法?
如何在 UseState 数组中定义嵌套数组的类型
定义的接口 -
interface ToyProps {
car: string | null;
doll: number | null;
}
interface SettingsProps {
[key: string]: ToyProps[];
}
Run Code Online (Sandbox Code Playgroud)
状态 -
const [state, setstate]:SettingsProps = React.useState({
toys: [
{
cars: "car 1",
doll: "doll 1",
},
{
cars: "car 2",
doll: "doll 3",
},
],
});
Run Code Online (Sandbox Code Playgroud)
我按照上面的方式定义了,但仍然出现类型错误
tl;dr - 如何通过跟踪强制重新渲染仅一个特定的子组件ref?
我有一个行表。我希望能够将鼠标悬停在行上并显示/隐藏行中的单元格,但只能在一段时间之后。
您只能在将鼠标悬停在整个表格上一段时间后(由onMouseEnter和触发)才能显示隐藏的悬停内容onMouseLeave。
一旦将鼠标悬停在特定的 上<Row>,如果父级允许,它应该显示额外的内容。
鼠标悬停在表格上的顺序:
isHovered现在是trueallowHover更改为trueallowHover和isHovered都是true,显示额外的行内容鼠标移出表格的顺序:
isHovered设置为falseallowHover更改为false此时,如果重新进入表,我们必须再次等待1秒才为allowHover真。一旦 和 都isHovered为allowHover真,则显示隐藏内容。一旦允许悬停,就不会有任何延迟:悬停在其上的行应立即显示隐藏的内容。
我试图useRef避免改变行父行的状态并导致所有子行的重新渲染
在行级别,悬停时,行应该能够检查是否允许悬停,而无需使用 props 重新渲染整个列表。我假设useEffect可以设置为跟踪该值,但它似乎不会在单个组件级别触发重新渲染。
换句话说,预期的行为是当前悬停在行上的行检测父级中的更改,并且仅重新渲染自身以显示内容。然后,一旦允许悬停,行为就很简单。将鼠标悬停在行上?揭示其内容。
以下是涉及的代码片段:
function Table() {
const allowHover = useRef(false);
const onMouseEnter = (e) => …Run Code Online (Sandbox Code Playgroud) 我在文件中定义了一个对象,如下所示:
export const items = {
first: false,
second: false,
third: false
}
Run Code Online (Sandbox Code Playgroud)
我在组件中使用它,如下所示:
import { items } from 'file';
const [elements, setElements] = useState(items);
Run Code Online (Sandbox Code Playgroud)
我有一个方法,当单击按钮时会调用该方法 - 该方法应该将所有值更改elements为true
使用以下更改值,但它不会触发组件的重新渲染(这就是我需要的)
Object.keys(elements).forEach(element => elements[element] = true);
Run Code Online (Sandbox Code Playgroud)
我如何使用setElements来更新 中的所有值elements?
use-state ×12
reactjs ×11
javascript ×8
react-hooks ×7
use-effect ×3
fetch-api ×1
react-native ×1
setinterval ×1
state ×1
types ×1
typescript ×1
use-ref ×1