【发布时间】:2020-08-15 19:40:53
【问题描述】:
使用带有 TypeScript 的 react 钩子,这是我想要做的最小表示:在屏幕上有一个按钮列表,当用户点击一个按钮时,我想将按钮的文本更改为“按钮clicked”,然后只重新呈现被点击的按钮。
我使用 useCallback 来包装按钮单击事件,以避免在每次渲染时重新创建单击处理程序。
这段代码按我想要的方式工作:如果我使用 useState 并在数组中维护我的状态,那么我可以在 useState 中使用 Functional update 并获得我想要的确切行为: p>
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;
但这是我的问题:在我的生产应用程序中,状态维护在一个对象中,我们使用 useReducer 挂钩来模拟类组件样式 setState ,我们只需要传入改变的属性。所以我们不必为每个动作都替换整个状态。
当尝试使用 useReducer 执行与以前相同的操作时,状态始终是陈旧的,因为 useCallback 的缓存版本是从设备列表为空时的第一次加载开始的。
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;
所以我的问题归结为:在 useCallback 中使用 useState 时,我们可以使用功能更新模式并捕获当前状态(而不是从缓存 useCallback 时开始) 这可以在不指定 useCallback 的依赖项的情况下实现。
我们如何在使用 useReducer 时做同样的事情?有没有办法在使用 useReducer 并且不指定 useCallback 的依赖项时获取 useCallback 中的当前状态?
【问题讨论】:
-
useState是mimic 类组件的setState合并行为的最简单选项。有什么原因,你为什么还要选择useReducer? -
谢谢,是的,我已经考虑过,并决定使用
useState确实。
标签: javascript reactjs typescript react-hooks