最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get previous props value with React Hooks - Stack Overflow

programmeradmin1浏览0评论

I am using usePreviousValue custom hook to get previous props value from my ponent:

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>)   
} 

But in this case, in prevCount I always have only the first count prop value when a ponent was rendered, and the next updated prop value is never assigned to it. Are there any ways to properly pare nextProp and prevProp with functional React ponents?

I am using usePreviousValue custom hook to get previous props value from my ponent:

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>)   
} 

But in this case, in prevCount I always have only the first count prop value when a ponent was rendered, and the next updated prop value is never assigned to it. Are there any ways to properly pare nextProp and prevProp with functional React ponents?

Share Improve this question asked Feb 1, 2021 at 10:31 Volodymyr HumeniukVolodymyr Humeniuk 3,80112 gold badges41 silver badges76 bronze badges 1
  • In React classes, ponentDidMount and ponentDidUpdate methods have optional parameters called prevProps and prevState that store previous props and state values – tomasxboda Commented Feb 1, 2021 at 10:50
Add a ment  | 

2 Answers 2

Reset to default 7

Your code sample seems to be working just fine. How exactly are you using the ponent? Try to run the snippet below:

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./ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

As previously answered, the easiest way to do it is using a custom hook:

import isEqual from "lodash/isEqual";
import { useEffect, useRef } from "react";

const useComponentDidUpdate = (callback, data, checkIfIsEqual) => {
    const prevData = useRef(data);

    useEffect(() => {
        const isTheSame = checkIfIsEqual ? isEqual(data, prevData) : undefined;
        callback(prevData.current, isTheSame);
        prevData.current = data;
    }, [data]);

    return null;
};

export default useComponentDidUpdate;

Then in your ponent:

const Component = ({age})=>{
const [state, setState] = useState({name: 'John', age})

useComponentDidUpdate(prevStateAndProps=>{
if(prevStateAndProps.age !== age || prevStateAndProps.state.name !== state.name){
   // do something
}

}, {state, age})

...
}

发布评论

评论列表(0)

  1. 暂无评论