我在 React 官方文档或 blagosphere 上还没有找到任何提及这一点的信息。
我认为当你有多个状态变量时你可以而且通常应该做这样的事情:
function MyComponent() {
const [foo, setFoo] = useState(0);
const [bar, setBar] = useState(1);
return (
<div>
<div onClick={() => setFoo(foo+1)}>{foo}</div>
<div onClick={() => setBar(bar+1)}>{bar}</div>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
是否允许并鼓励这样做,而不是使用useState一个包含state字段foo和的包罗万象的对象来调用一次bar?如果允许并鼓励这样做,那么useState每次调用时如何知道它是指已存储的foo还是已存储的bar?
我也有基本相同的问题useCallback。我想知道,如果我useCallback在同一个组件中调用两次以创建两个不同的回调,如何知道useCallback我要引用之前定义的函数与创建新函数,并且如果引用已使用的函数,则需要返回记忆的函数的版本,它如何知道两者中的哪一个?特别是如果两个回调具有相同的依赖项列表?
在反应中,我使用功能组件,并且有两个函数(getBooks)和(loadMore)
getBooks从端点获取数据。但是,当我loadMore在函数内单击按钮调用getBooks函数(loadMoreClicked)时,即使在延迟(5秒)调用它之后,它也不会更改它使用以前的状态。但是当我loadMore再次打电话时,状态发生了变化,一切正常。
有人可以解释为什么初始调用 (getBooks) 时的 (loadMoreClicked) 即使在 5 秒延迟后调用它也没有更新。
function component() {
const [loadMoreClicked, setLoadMore] = useState(false);
const getBooks = () => {
const endPoint = `http://localhost/getBooks`; //this is my end point
axios
.get(endPoint, {
params: newFilters
})
.then(res => {
console.log(loadMoreClicked); //the (loadMoreClicked) value is still (false) after (5 sec)
})
.catch(err => {
console.log(err);
});
};
const loadMore = () => {
setLoadMore(true); //here i am changing (loadMoreClicked) value to (true) …Run Code Online (Sandbox Code Playgroud) 我需要将项目连接到存储在 React 组件状态中的数组。我有一个关于 stackblitz 的例子,我不明白为什么数组没有增长,因为我使用扩展运算符添加元素以连接到现有数组。任何帮助表示赞赏
链接:https : //stackblitz.com/edit/react-usestate-example-ebzt6g?file=index.js
import React from 'react';
import { useState, useEffect } from 'react';
import { render } from 'react-dom';
import './style.css';
const App = () => {
const [name, setName] = useState('React');
const [coords, setCoords] = useState([]);
const success = (position) => {
// setCoords(coords.concat(position.coords))
setCoords([
...coords,
position.coords
])
console.log("success! position=", position);
}
useEffect(() => {
console.log("useEffect -> coords =", coords);
});
useEffect(() => {
setInterval(() => {
success({coords : {latitude: Math.random()*51, longitude: …Run Code Online (Sandbox Code Playgroud) React useState,当我设置状态时,一些奇怪的<canvas>附加到 main <html>!
import React, { useState } from 'react';
import './style.scss';
export default () => {
const [auth, setAuth] = useState(false);
const handleAuth = () => setAuth(true);
return (
<header>
<button onClick={handleAuth}>handle auth</button>
</header>
);
};
Run Code Online (Sandbox Code Playgroud)
单击按钮时,奇怪的内容<canvas>会附加到<html>开头。
<html lang="en">
<canvas style="inset: 0px; pointer-events: none; position: fixed; z-index: 1000000000;" width="1920" height="514"></canvas>
<head>
...
Run Code Online (Sandbox Code Playgroud) 我正在开发一个 React 应用程序,它根据我设置的配置文件列表生成随机配置文件。
我想要完成的是随机生成一个 1-3 之间的数字,它代表我的数组中的对象。然后将随机生成的数字与属性一起传入以指定 useState 的值。尝试执行此操作时出现错误。
个人资料卡片.js
import { useState } from "react";
const ProfileCard = () => {
const [profile, setProfile] = useState("/images/image-bob2.jpg",)
const [name, setName] = useState("Bob James")
const [userStats, setUserStats] = useState("80K 803K 1.4K")
const [city, setCity] = useState("Houston")
const influencers = [
{id: 1, pic:"/images/image-bob2.jpg", name:"Bob James", age: "42", city: "Houston", stats: "65K 750K 3.7K" },
{id: 2, pic:"/images/image-jim2.jpg", name:"Jim Thompson", age: "54", city: "Chicago", stats: "45K 700K 2.3K" },
{id: 3, pic:"/images/image-victor.jpg", name:"Victor …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个带有删除按钮的购物清单,但是当我单击它时,其他项目将被删除,并且以前的值仍保留在屏幕上,即使第二次删除也是如此。请假设自定义按钮和图标已经是单独的包这是代码 -
import React, { useState } from 'react';
import { CButton, CDeleteButton } from '@custom/pkg';
const ShoppingList = () => {
const [state, setState] = useState(
[{ name: 'Apple', price: 60 }, { name: 'Banana', price: 20 }]
)
return (
<>
<h2>Product List</h2>
{state.map(({name, price}, idx) => (
<>
<div key={idx}>
<div>{name}</div>
<div>{price}</div>
<div>
<CButton id={idx} onClick={() => {
setState((prev) => [...prev.splice(idx, 1)])
}}>
<CDeleteButton/>
</CButton>
</div>
</div>
</>
))}
</>
)
}
export default ShoppingList;
Run Code Online (Sandbox Code Playgroud)
该组件被导入到模态组件中并进行渲染。如果我删除"Apple" …
我按照这个线程中的答案尝试更新我在 React 中的深层嵌套对象。 React:使用 Hooks 设置深度嵌套对象的状态
那里似乎有魅力,但在执行以下操作时会以某种方式破坏我:
我有一个表,其中填充了定义如下的数组中的项目:
const [items, setItems] = useState([
{
selected: false,
title: 'Item 1',
status: 'new'
},
{
selected: false,
title: 'Item 2',
status: 'used'
},
]);
Run Code Online (Sandbox Code Playgroud)
当从该列表中选择一个项目时,会调用此函数来更新selected具有索引的对象的变量,i如下所示:
const select = (e) => {
const i = e.target.getAttribute('data-index');
setItems((prevState) => {
prevState[i].selected = !prevState[i].selected;
return [...prevState];
});
};
Run Code Online (Sandbox Code Playgroud)
这只会工作一次。如果我select第二次或此后的任何时间触发return [...prevState],都会以某种方式保持返回状态不变。(永远selected保留true)。我无法解决这个问题。
items附加到一个组件,List如下所示:
<List
items={items}
/>
Run Code Online (Sandbox Code Playgroud)
和内部List(缩写代码):
{items.map((item, i) => …Run Code Online (Sandbox Code Playgroud) 我正在使用组件函数和 useState 使用 React 来处理客户端验证表单。问题是,当我单击提交时,handleSubmit 会更新带有错误的“验证”状态,但当状态更改时它们不会呈现。仅当我在输入字段中输入一些值时才会呈现它们。我该如何解决这个问题?
您可以在下面找到代码:
import React, { useState } from 'react';
function RegistrationView() {
const [inputValues, setInputValue] = useState({
fName: '',
lName: '',
email: '',
password: '',
confirmPassword: '',
});
const [validation, setValidation] = useState({
fName: '',
lName: '',
email: '',
password: '',
confirmPassword: '',
});
//handle submit updates
function handleChange(event) {
const { name, value } = event.target;
setInputValue({ ...inputValues, [name]: value });
}
const handleSubmit = (e) => {
e.preventDefault();
let errors = validation;
//first …Run Code Online (Sandbox Code Playgroud) 我有数据试图获取并与下面的代码一起使用,但是当我记录记录的值时,我首先得到一个空数组,然后得到我获取的对象。因此,我无法在我的应用程序中访问该对象的信息。
const [records, setRecords] = useState([]);
useEffect(() => {
async function getRecords() {
const response = await fetch(`http://localhost:5000/record`);
if (!response.ok) {
const message = `An error occurred: ${response.statusText}`;
window.alert(message);
return;
}
const records = await response.json();
setRecords(records);
}
getRecords();
return;
}, []);
console.log(records);
Run Code Online (Sandbox Code Playgroud) const user = useSelector((state) => state.user);
const [allPost, setAllPost] = useState([]);
const getAllPost = async () => {
const q = query(collection(db, "posts", "post", user.user.email));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
console.log(doc.data());
const newPost = doc.data();
setAllPost([...allPost, newPost]);
});
};
useEffect(() => {
getAllPost();
}, []);
Run Code Online (Sandbox Code Playgroud)
我的 firestore 中有四个文档,但 setState 仅返回一个文档,尽管使用 forEach 循环我可以看到所有四个对象
reactjs ×10
use-state ×10
javascript ×6
react-hooks ×3
arrays ×2
ecmascript-6 ×1
html ×1
use-effect ×1
usecallback ×1