【问题标题】:Get previous props value with React Hooks使用 React Hooks 获取先前的 props 值
【发布时间】:2021-02-01 10:31:44
【问题描述】:

我正在使用usePreviousValue 自定义钩子从我的组件中获取以前的道具值:

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


const MyComponent = ({ count }) => {
   const prevCount = usePreviousValue(count)

   return (<div> {count} | {prevCount}</div>)   
} 

但是在这种情况下,在 prevCount 中,当渲染组件时,我总是只有第一个 count 属性值,而下一个更新的属性值永远不会分配给它。有什么方法可以正确地将 nextProp 和 prevProp 与功能性 React 组件进行比较?

【问题讨论】:

  • 在 React 类中,componentDidMount 和 componentDidUpdate 方法具有可选参数,称为 prevProps 和 prevState,用于存储以前的 props 和 state 值

标签: javascript reactjs react-hooks


【解决方案1】:

您的代码示例似乎运行良好。您究竟是如何使用该组件的?尝试运行下面的sn-p:

const { useEffect, useRef, useState } = React;

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


const MyComponent = ({ count }) => {
   const prevCount = usePreviousValue(count);

   return (<div> {count} | {prevCount}</div>);
} 

function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <MyComponent count={count} />
      <button
        onClick={() => setCount((prevCount) => prevCount + 1)}
      >
        Count++
      </button>
    </div>
  );
}

ReactDOM.render(<App />, document.body);
<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多