Title rewritten as: Variables are not updated when using useState() hook
P粉066224086
P粉066224086 2023-09-10 18:43:16
0
1
592

I'm working on a social network project using React.

I wanted to replace a component from a class component to a function component and use hooks, and then a global problem occurred:

When I switch to a new user, the page displays the status of the previous user

I used the useState() hook, debugged everything, but for some reason when a new state component is rendered it doesn't update

const ProfileStatus = (props) => {
  const [edditMode, setEdditMode] = useState(false);
  const [status, setValue] = useState(props.status || "Empty");

  const onInputChange = (e) => {
    setValue(e.target.value);
  };
  const activateMode = () => {
    setEdditMode(true);
  };
  const deactivateMode = () => {
    setEdditMode(false);
    props.updateUserStatus(status);
  };

I thought the problem was that the container component was still a class component, but after redoing it, nothing changed.

P粉066224086
P粉066224086

reply all(1)
P粉674876385

One solution is to use the useEffect hook to trigger an update when the property changes. You can use this hook to compare the current property with the previous property and then update the state in the state.

You can use this as a reference and make adjustments based on your own code.

const ProfileStatus = (props) => {
  const [edditMode, setEdditMode] = useState(false);
  const [status, setValue] = useState(props.status || "Empty");

  useEffect(() => {
    setValue(props.status || "Empty");
  }, [props.status]);

  const onInputChange = (e) => {
    setValue(e.target.value);
  };
  const activateMode = () => {
    setEdditMode(true);
  };
  const deactivateMode = () => {
    setEdditMode(false);
    props.updateUserStatus(status);
  };
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template