这是所有新反应开发人员中的一个流行问题,但不知何故我无法理解可用解决方案背后的逻辑。我正在尝试使用钩子更新状态变量并尝试读取更新后的值,但它总是返回先前的值而不是新值。下面是我的代码执行顺序。
onClick={setTransactionAccountId}
Run Code Online (Sandbox Code Playgroud)
单击按钮时,它会执行以下代码并更新状态,但会console.log显示旧值。
const [accountId, setAccountId] = useState(0);
const setTransactionAccountId = e => {
console.log("Clicked ID:", e.currentTarget.value);
setAccountId(e.currentTarget.value);
console.log("accountId:", accountId);
};
Run Code Online (Sandbox Code Playgroud)
控制台日志:
单击的 ID:0 帐户 ID:0
单击的 ID:1 accountId:0
谁能告诉我这种行为背后的原因以及如何解决它。
我正在尝试更新我的“state”数组并使用“setState”将 String 类型的项目插入其中,但它不起作用。
我知道这不适用于push()。
我还尝试使用扩展运算符更新我的“状态”数组,但它也不起作用。
这是我的代码:
import React, { useState } from 'react';
import _, { debounce } from 'lodash';
export default function Search() {
const [state, setState] = useState([])
const handleChange = debounce(async (value) => {
const url = `http://localhost:3100/`
if (value == '') {
return
}
let response = await fetch(url, {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify({ value })
})
let test = await response.json()
console.log(test)
setState(state.concat(test))
// setState([...state, test]) it also doesn't work …Run Code Online (Sandbox Code Playgroud) 我在 ReactJS 商店中有以下产品列表:
{productsList.map((product) => (
<ProductItem
product={product}
/>
)}
Run Code Online (Sandbox Code Playgroud)
当我在此列表中添加更多产品时,滚动位置将转到列表的末尾。添加更多产品的代码:
function nextPage() {
getMoreProducts().then((newProducts)=> {
setProductsList(productsList.concat(newProducts))
})
}
Run Code Online (Sandbox Code Playgroud)
我需要保持滚动位置,因为这样用户必须滚动到顶部才能看到加载的新产品。
我尝试存储滚动位置,但更改是在列表增长之前完成的,所以什么也没有发生:
function nextPage() {
const actualScrollPosition = window.pageYOffset
getMoreProducts().then((newProducts)=> {
setProductsList(productsList.concat(newProducts)) //<- setState from React is async.
window.scroll({ top: actualScrollPosition, behavior: "smooth" });
})
}
Run Code Online (Sandbox Code Playgroud) 我试图根据输入中是否有文本来启用或禁用按钮,但似乎无法实现。当我在按钮功能的禁用属性中手动设置 {true OR false} 时,它工作正常,但我对如何根据输入的内容动态设置它感到非常困惑。
非常欢迎任何指导!
这是我的应用程序代码
import { useState } from "react";
function Input (props){
const { onChange, value } = props
return (<input value={value} onChange={onChange} type="text" placeholder="Add a ToDo" maxLength="50"/>)
}
function Button (props) {
const {onChange, state, text} = props
return (<button disabled={false} onChange={onChange}>{text}</button>)
}
function App() {
const [text, setText] = useState("");
const [state, setSate] = useState(true);
const handleChange = (event) => {
if (!setText(event.target.value)) {
setSate(false);
} else {
setSate(true);
}
};
return (
<div …Run Code Online (Sandbox Code Playgroud)与 from 类不同state,您不限于单个对象。使用useState,您可以为每种情况创建单独的值,如下所示:
const [name, setName] = useState('John');
const [email, setEmail] = useState('john@example.com');
const [age, setAge] = useState(25);
Run Code Online (Sandbox Code Playgroud)
但是,我发现这非常肮脏,并且更喜欢只使用一个useState用对象初始化的:
const [user, setUser] = useState(
{ name: 'John', email: 'john@example.com', age: 25 }
);
Run Code Online (Sandbox Code Playgroud)
我知道没有严格的限制并且useState可以存储对象,但是在类组件中,当您使用更新状态时this.setState,它会与旧的合并。使用 时useState,更新函数会用新状态替换旧状态(没有合并)。
我经常像下面这样实现:
setUser(prevStat => ({
...prevState,
name: 'Daniel'
}));
Run Code Online (Sandbox Code Playgroud)
如果我是正确的,更新对象状态将重新渲染对象状态的所有字段,这对于应用程序来说可能会更昂贵?
当我尝试从 redux 状态设置初始值时,文本组件上没有任何内容,但我可以在控制台上看到该值
const Profile = props => {
const userName = useSelector(userSelector);
const [name, setName] = useState(userName);
console.log(userName);
return (
<Text>{name}</Text>
);
};
Run Code Online (Sandbox Code Playgroud) 在功能组件中,我们对类组件使用 useState 而不是 this.setState。但据我所知,useState 一次只能设置一个状态,而 setState 可以一次设置多个状态(例如 this.setState({a1: true, a2: false}))。
这是否意味着如果您想使用 useState 同时设置两个状态,您会得到双重重新渲染,这是低效的?有办法解决这个问题吗?
javascript react-native react-functional-component use-state
如果我有一个变量,其值可以根据另一个属性的值完全派生,那么初始化计算变量与使用useState/的组合useEffect来跟踪变量是否有任何后果/陷阱?让我用一个人为的例子来说明:
/**
* ex paymentAmounts: [100, 300, 400]
*/
const Option1 = ({paymentAmounts}) => {
const [average, setAverage] = useState(paymentAmounts.reduce((acc, curr) => curr + acc, 0) / paymentAmounts.length)
useEffect(() => {
setAverage(paymentAmounts.reduce((acc, curr) => curr + acc, 0) / paymentAmounts.length)
}, [paymentAmounts])
return (
<div>
Average: {average}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
或者更简单地说
/**
* ex paymentAmounts: [100, 300, 400]
*/
const Option2 = ({paymentAmounts}) => {
const average = paymentAmounts.reduce((acc, curr) => curr + acc, 0) / …Run Code Online (Sandbox Code Playgroud) 我正在研究 React hooks 并在代码中插入一些控制台日志,以更好地理解渲染流程。然后我开始模拟发送相同值的 setState 效果,看看 React 是否会再次渲染它。
import { useState } from "react";
function ManComponent() {
/* States */
const [shirt, setShirt] = useState("Blue Shirt");
console.log("Rendering man with "+shirt);
/* Actions */
const changeShirt = (newShirt) => {
console.log("[Man] Changing shirt from "+shirt+" to "+newShirt);
setShirt(newShirt);
};
return (
<div>
<p>The man is using: {shirt}</p>
<div>
<button onClick={() => changeShirt("Red Shirt")}>Change to red shirt</button>
<button onClick={() => changeShirt("Blue Shirt")}>Change to blue shirt</button>
</div>
</div>
);
}
export default function …Run Code Online (Sandbox Code Playgroud) 我正在使用 React 构建一个简单的时钟应用程序。目前该countDown()功能有效,但我希望用户能够通过按下按钮来停止/启动时钟。我有一个名为的状态布尔值,paused当用户单击按钮时该状态布尔值会反转。问题在于,在 的值反转后,对传递给的函数内部paused的引用似乎正在访问 的默认值,而不是更新后的值。pausedcountDown()setInterval()paused
function Clock(){
const [sec, setSecs] = useState(sessionLength * 60);
const [paused, setPaused] = useState(false);
const playPause = () => {
setPaused(paused => !paused);
};
const countDown = () => {
if(!paused){
setSecs(sec => sec - 1)
}
}
useEffect(() => {
const interval = setInterval(() => {
countDown();
}, 1000);
return () => {
clearInterval(interval);
};
}, []);
Run Code Online (Sandbox Code Playgroud)
setState()我假设它与 React 中调用的异步性质和/或使用正则表达式时范围/上下文的性质有关。然而,我无法通过阅读与这些概念相关的文档来确定发生了什么。
我可以想到一些解决方法,让我的应用程序能够按需要运行。但是我想了解我当前的方法有什么问题。我将不胜感激任何人都可以阐明这一点!
use-state ×10
reactjs ×9
javascript ×8
react-hooks ×5
react-native ×3
use-effect ×2
console ×1
ecmascript-6 ×1
react-redux ×1
setinterval ×1
state ×1
togglebutton ×1