首页 > 解决方案 > React:usePrevious 钩子仅在组件中有 1 个状态时才有效。如果有多个状态,如何使其工作?

问题描述

文档建议以下获取先前状态:

function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  return <h1>Now: {count}, before: {prevCount}</h1>;
}

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

根据我的理解,只有在组件中只有一个状态时才能正常工作。但是,如果有多个状态,请考虑以下情况:

import "./styles.css";
import React, { useState, useEffect, useRef, useContext } from "react";


function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

export default function App() {
  const [count, setCount] = useState(0);
  const [foo, setFoo] = useState(0);
  const prevCount = usePrevious(count);

  return (
    <div>
    <button onClick={() => setFoo(f => f+1)}> Update foo </button>
     <h1>Now: {count}, before: {prevCount}</h1>
  </div>);
}

沙盒:https ://codesandbox.io/s/little-feather-wow4m

当一个不同的foo状态

当有多个状态时,有没有办法可靠地获取状态/道具的先前值?

标签: javascriptreactjs

解决方案


我不认为这是正确的做法。

如何设置状态并返回为您处理此逻辑的自定义设置器函数的自定义钩子。

function useStateWithPrevious(initial) {
  const [value, setValue] = useState(initial)
  const [prev, setPrev] = useState(initial)

  function setValueAndPrev(newValue) {
    if (newValue === value) return // optional, depends on the logic you want.
    setPrev(value)
    setValue(newValue)
  }

  return [prev, value, setValueAndPrev]
}

您会使用如下:

function MyComponent() {
  const [prevCount, count, setCount] = useStateWithPrevious(0)
}

推荐阅读