- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用带有 TypeScript 的 react 钩子(Hook),这是我正在尝试做的最小表示:在屏幕上有一个按钮列表,当用户单击一个按钮时,我想将按钮的文本更改为“按钮单击”和然后 只重新渲染被点击的按钮 .
我正在使用 useCallback 来包装按钮单击事件,以避免在每次渲染时重新创建单击处理程序。
这段代码按我想要的方式工作:如果我使用 useState 并在数组中维护我的状态,那么我可以使用 Functional update在 useState 并获得我想要的确切行为:
import * as React from 'react';
import { IHelloWorldProps } from './IHelloWorldProps';
import { useEffect, useCallback, useState } from 'react';
import { PrimaryButton } from 'office-ui-fabric-react';
interface IMyButtonProps {
title: string;
id: string;
onClick: (clickedDeviceId: string) => (event: any) => void;
}
const MyButton: React.FunctionComponent<IMyButtonProps> = React.memo((props: IMyButtonProps) => {
console.log(`Button rendered for ${props.title}`);
return <PrimaryButton text={props.title} onClick={props.onClick(props.id)} />;
});
interface IDevice {
Name: string;
Id: string;
}
const HelloWorld: React.FunctionComponent<IHelloWorldProps> = (props: IHelloWorldProps) => {
//If I use an array for state instead of object and then use useState with Functional update, I get the result I want.
const initialState: IDevice[] = [];
const [deviceState, setDeviceState] = useState<IDevice[]>(initialState);
useEffect(() => {
//Simulate network call to load data.
setTimeout(() => {
setDeviceState([{ Name: "Apple", Id: "appl01" }, { Name: "Android", Id: "andr02" }, { Name: "Windows Phone", Id: "wp03" }]);
}, 500);
}, []);
const _deviceClicked = useCallback((clickedDeviceId: string) => ((event: any): void => {
setDeviceState(prevState => prevState.map((device: IDevice) => {
if (device.Id === clickedDeviceId) {
device.Name = `${device.Name} clicked`;
}
return device;
}));
}), []);
return (
<React.Fragment>
{deviceState.map((device: IDevice) => {
return <MyButton key={device.Id} title={device.Name} onClick={_deviceClicked} id={device.Id} />;
})}
</React.Fragment>
);
};
export default HelloWorld;
import * as React from 'react';
import { IHelloWorldProps } from './IHelloWorldProps';
import { useEffect, useCallback, useReducer, useState } from 'react';
import { PrimaryButton } from 'office-ui-fabric-react';
interface IMyButtonProps {
title: string;
id: string;
onClick: (clickedDeviceId: string) => (event: any) => void;
}
const MyButton: React.FunctionComponent<IMyButtonProps> = React.memo((props: IMyButtonProps) => {
console.log(`Button rendered for ${props.title}`);
return <PrimaryButton text={props.title} onClick={props.onClick(props.id)} />;
});
interface IDevice {
Name: string;
Id: string;
}
interface IDeviceState {
devices: IDevice[];
}
const HelloWorld: React.FunctionComponent<IHelloWorldProps> = (props: IHelloWorldProps) => {
const initialState: IDeviceState = { devices: [] };
//Using useReducer to mimic class component's this.setState functionality where only the updated state needs to be sent to the reducer instead of the entire state.
const [deviceState, setDeviceState] = useReducer((previousState: IDeviceState, updatedProperties: Partial<IDeviceState>) => ({ ...previousState, ...updatedProperties }), initialState);
useEffect(() => {
//Simulate network call to load data.
setTimeout(() => {
setDeviceState({ devices: [{ Name: "Apple", Id: "appl01" }, { Name: "Android", Id: "andr02" }, { Name: "Windows Phone", Id: "wp03" }] });
}, 500);
}, []);
//Have to wrap in useCallback otherwise the "MyButton" component will get a new version of _deviceClicked for each time.
//If the useCallback wrapper is removed from here, I see the behavior I want but then the entire device list is re-rendered everytime I click on a device.
const _deviceClicked = useCallback((clickedDeviceId: string) => ((event: any): void => {
//Since useCallback contains the cached version of the function before the useEffect runs, deviceState.devices is always an empty array [] here.
const updatedDeviceList = deviceState.devices.map((device: IDevice) => {
if (device.Id === clickedDeviceId) {
device.Name = `${device.Name} clicked`;
}
return device;
});
setDeviceState({ devices: updatedDeviceList });
//Cannot add the deviceState.devices dependency here because we are updating deviceState.devices inside the function. This would mean useCallback would be useless.
}), []);
return (
<React.Fragment>
{deviceState.devices.map((device: IDevice) => {
return <MyButton key={device.Id} title={device.Name} onClick={_deviceClicked} id={device.Id} />;
})}
</React.Fragment>
);
};
export default HelloWorld;
最佳答案
您可以调度一个将由 reducer 调用的函数并获取传递给它的当前状态。像这样的东西:
//Using useReducer to mimic class component's this.setState functionality where only the updated state needs to be sent to the reducer instead of the entire state.
const [deviceState, dispatch] = useReducer(
(previousState, action) => action(previousState),
initialState
);
//Have to wrap in useCallback otherwise the "MyButton" component will get a new version of _deviceClicked for each time.
//If the useCallback wrapper is removed from here, I see the behavior I want but then the entire device list is re-rendered everytime I click on a device.
const _deviceClicked = useCallback(
(clickedDeviceId) => (event) => {
//Since useCallback contains the cached version of the function before the useEffect runs, deviceState.devices is always an empty array [] here.
dispatch((deviceState) => ({
...deviceState,
devices: deviceState.devices.map((device) => {
if (device.Id === clickedDeviceId) {
device.Name = `${device.Name} clicked`;
}
return device;
}),
}));
//no dependencies here
},
[]
);
const { useCallback, useReducer } = React;
const App = () => {
const [deviceState, dispatch] = useReducer(
(previousState, action) => action(previousState),
{ count: 0, other: 88 }
);
const click = useCallback(
(increase) => () => {
//Since useCallback contains the cached version of the function before the useEffect runs, deviceState.devices is always an empty array [] here.
dispatch((deviceState) => ({
...deviceState,
count: deviceState.count + increase,
}));
//no dependencies here
},
[]
);
return (
<div>
<button onClick={click(1)}>+1</button>
<button onClick={click(2)}>+2</button>
<button onClick={click(3)}>+3</button>
<pre>{JSON.stringify(deviceState)}</pre>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
useReducer
的方式。并且不要找到你不使用
useState
的理由而在这种情况下。
关于javascript - 使用useReducer时如何在useCallback中获取当前状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61540401/
为了深入研究 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
我是一名优秀的程序员,十分优秀!