- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的印象是 useState
和 useReducer
的工作方式相似,只是当状态是复杂/嵌套对象时我们应该使用 useReducer。
但是今天我发现了一个奇怪的行为,我正在循环一个数组并将值设置为一个状态对象。我使用 useState
和 useReducer
做了同样的例子。
使用useState
:它只是将数组中的最后一个值推送到状态对象,因为useState本质上是异步的,所以当我们在循环中设置状态时,它可能无法根据之前的正确更新状态。所以你只得到状态中的最后一个对象。
使用 useReducer
:我期待 useReducer 具有相同的行为,但使用 useReducer,当我们从循环内 dispatch
操作时,它似乎可以正确设置状态。所以在这里你可以得到状态中的所有对象。
使用状态
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
const [students, setStudents] = React.useState({});
const createStudents = () => {
const ids = [1,2,3];
const names = ['john', 'michael', 'greg']
for(let i = 0; i < 3; i++){
const student = {[ids[i]]: names[i]};
setStudents({...students, ...student})
}
}
return (
<div className="App">
<button onClick={createStudents}>Create Students</button>
<br />
{JSON.stringify(students)}
</div>
);
}
使用Reducer
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
const studentReducer = (state, action) => {
switch (action.type) {
case 'ADD':
return {...state, students: {...state.students, ...action.payload}};
default:
throw new Error();
}
}
const [students, dispatch] = React.useReducer(studentReducer, {students: {}});
const createStudents = () => {
const ids = [1,2,3];
const names = ['john', 'michael', 'greg']
for(let i = 0; i < 3; i++){
const student = {[ids[i]]: names[i]};
dispatch({type: 'ADD', payload: student})
}
}
return (
<div className="App">
<button onClick={createStudents}>Create Students</button>
<br />
{JSON.stringify(students)}
</div>
);
}
最佳答案
I was in a impression that both useState and useReducer works similarly
这种印象是正确的。如果我记得,useState
甚至 calls useReducer
,所以真的 useState
基本上是 useReducer 的一个特例
(我之前在 react 的源代码中查找过这个,但我找不到它来提供链接)。
您看到的行为与它是同步还是异步无关,而与您是根据闭包中的值计算新状态还是根据最新值计算新状态有关。考虑这段代码:
const [students, setStudents] = React.useState({});
//... some code omitted
setStudents({...students, ...student})
注意students是一个const
。它永远不会改变,即使你调用 setStudents
也是如此。如果您只设置一次状态,那并不是真正的问题:您将复制学生,添加一个新学生,然后将其传递。然后组件重新呈现。在该新渲染上,将创建一个新的局部变量,其中包含一个学生的新对象。然后,新渲染中的代码可以与该对象与一名学生进行交互,并可能创建一个与两名学生一起使用的对象。
但是如果你在一个循环中执行它,那么每次通过循环你都是从空对象开始的。您复制空对象,添加学生 A,并告诉 react 设置状态。 students
没有改变,因此您再次复制相同的空对象,并添加学生 B。请注意,第二次不包括 A。最终循环结束,唯一的 setStudents最重要的是最后一个。
设置状态时,您可以使用另一种形式。你传入一个函数,react 将使用最新值调用该函数:
setStudents(previous => {
return {
...previous,
...student
}
});
使用这种方法,previous 以空对象开始,然后添加学生 A。然后在下一次循环中,previous 现在是包含学生 A 的对象,然后添加学生 B。所以当大功告成,您将拥有所有学生,而不仅仅是最后一个。
回到你关于 useState 和 useReducer 的问题:它们不同的原因是 useReducer 总是使用回调形式。 reducer 函数将始终以最新状态传递,因此您基于该状态计算新状态,而不是基于任何 students
等于上次呈现组件的时间。如果您重做代码以使用上面所示的回调,您也可以在 useState 中使用相同的东西。
关于javascript - 与 useState 的异步性质相比,React 的 useReducer 是同步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64538271/
为了深入研究 React Hooks,我决定尝试制作 snake 并使用 useReducer/useContext 状态管理。 现在,我被阻止在需要方向键来更改事件图 block 状态的地方。在 u
现在我尝试使用 useReducer 创建一种管理状态和功能的新方法,但现在发现问题是“Hooks 只能在函数组件的主体内部调用”有什么办法可以解决这个问题吗? // App Component im
我正在尝试创建一个可重复使用的useReducer与打字 Hook 。 这是我当前的代码: type State = { data?: T isLoading: boolean error
我正在编写一个自定义 Hook 来从 API 获取一些数据。如果可能的话,我希望返回的数据是类型安全的。这可以用泛型来完成吗? type Action = { type: 'PENDING' } |
我正在尝试创建一个可重复使用的useReducer与打字 Hook 。 这是我当前的代码: type State = { data?: T isLoading: boolean error
来自docs : [init, the 3d argument] lets you extract the logic for calculating the initial state outsid
我已经实现了一种相当简单的方法来将撤消添加到 useReducer 中,方法如下: export const stateMiddleware = reducerFunc => { return f
根据 React 文档: useReducer is usually preferable to useState when you have complex state logic that inv
我注意到在许多 useReducer 示例中,展开运算符在 reducer 中的使用方式如下: const reducer = (state, action) => { switch (actio
我想使用 React.useReducer 来更新状态。我的状态是一组对象。触发更新操作时,不仅更新所需索引中的值,而且更新所有这些值。我只想更新指定数组索引中的值。我该怎么做? 点击button1后
我有一个状态对象,其中包含一个名为 rows 的数组。该数组包含一个对象列表: {_id: "5e88ad4c5f6f7388d50b9480", stampa: "Confezione", S: 0
使用 useReducer 时是否可以使用调度功能发送多个操作? Hook react ?我尝试将一系列操作传递给它,但这会引发未处理的运行时异常。 明确地说,通常会有一个初始状态对象和一个 redu
我有这些: export type DataItemChild = { id: number; title:string; checked?: boolean; }; 请注意,子项可以在此
假设我实现了一个简单的全局加载状态,如下所示: // hooks/useLoading.js import React, { createContext, useContext, useReducer
我不仅需要在 ComponentDidMount 上使用 loadData() 从服务器获取数据,还需要在 onFiltersClear、onApplyFilters 和 方法之后使用>onPageC
如果我在使用 时需要添加一些副作用,我想知道我有哪些选择useReducer 钩。 例如,有一个 TODO-app: const initialState = {items: []}; const r
useReducer is usually preferable to useState when you have complex state logic that involves multipl
场景 我有一个返回操作的自定义 Hook 。 父组件“Container”利用自定义钩子(Hook)并将操作作为 prop 传递给子组件。 问题 当从子组件执行操作时,实际调度会发生两次。 现在,如果
我正在尝试使用新的 React useReducer API 获取一些数据,但卡在了我需要异步获取它的阶段。我只是不知道怎么办:/ 如何将数据获取放在 switch 语句中,或者这不是应该完成的方法?
这个问题在这里已经有了答案: Why is localStorage getting cleared whenever I refresh the page? (3 个答案) 关闭 5 个月前。 H
我是一名优秀的程序员,十分优秀!