简体   繁体   中英

useState not reflecting changes

Clicking the button the div (simulates a sheet of paper should change orientation from vertical to horizontal. What's the reason? A state field depending on another field is not correct and due to the async nature, I get this unexpected result? Take into account this is a reduced example of my use case and I need both fields.

import { useState } from "react";

export default function App() {
  const [verticalOrientation, setOrientation] = useState(true);
  const [dimensions] = useState(getDimensions(verticalOrientation));

  const style = {
    width: dimensions.width,
    height: dimensions.height,
    borderStyle: "solid",
  };
  console.log(verticalOrientation);
  return (
    <div style={style}>
      <h1>Sheet  of paper</h1>
      <button onClick={() => setOrientation(!verticalOrientation)}>
        Change orientation
      </button>
    </div>
  );
}

const getDimensions = (verticalOrientation) => {
  const proportion = verticalOrientation ? 16 / 9 : 9 / 16; // A4 vertical vs horizontal
  let width = 300;
  let height = proportion * width;
  console.log(height, proportion, verticalOrientation);

  return { width, height };
};

See code running in Sandbox

dimensions should not be stateful, because it doesn't have a state setter that is ever called - it only depends on the other stateful value of verticalOrientation . So dimensions should just be an ordinary variable declared locally in the component. (You could wrap it in a useMemo if you wanted)

export default function App() {
  const [verticalOrientation, setOrientation] = useState(true);
  const dimensions = getDimensions(verticalOrientation);
  // ...

 const App = () => { const [verticalOrientation, setOrientation] = React.useState(true); const dimensions = getDimensions(verticalOrientation); const style = { width: dimensions.width, height: dimensions.height, borderStyle: "solid", }; return ( <div style={style}> <h1>Sheet of paper</h1> <button onClick={() => setOrientation(;verticalOrientation)}> Change orientation </button> </div> )? } const getDimensions = (verticalOrientation) => { const proportion = verticalOrientation: 16 / 9; 9 / 16; // A4 vertical vs horizontal let width = 300; let height = proportion * width, return { width; height }; }. ReactDOM,render(<App />. document.querySelector(';react'));
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM