【问题标题】:How to get current state inside useCallback when using useReducer?使用useReducer时如何在useCallback中获取当前状态?
【发布时间】: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 中的当前状态?

【问题讨论】:

  • useStatemimic 类组件的setState 合并行为的最简单选项。有什么原因,你为什么还要选择useReducer
  • 谢谢,是的,我已经考虑过,并决定使用useState 确实。

标签: javascript reactjs typescript react-hooks


【解决方案1】:

您可以调度一个将由 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

【讨论】:

  • 谢谢,我已将此标记为答案,但您说得对,useState 可能更适合这里,所以我决定使用它而不是 useReducer。创建了一个自定义钩子,它围绕 useState 并公开函数以将新状态与现有状态合并,或者如果新状态依赖于现有状态,则使用调度方法。
猜你喜欢
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 2016-12-02
  • 2018-07-23
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多