处于状态的React Node记住道具

 收藏

我在调试此代码时遇到麻烦。

我有一个App组件:

function App() {
  const [state, setState] = useState(0);

  const onSelectItem = () => {
    console.log("🐞: onSelectItem -> currentState", state);
  };

  // items is an array of ReactNode: button, when click on it. It will log the currentState.
  const items = ["FirstItem", "SecondItem"].map(item =>  (
      <button key={item} onClick={() => onSelectItem()}>
        {item}
      </button>
    );
  );

  return (
    <div className="App">
      <Menu items={items} />
      <hr />
      <button onClick={() => setState(prevState => prevState + 1)}>Change State</button>
    </div>
  );
}

My Menu components will receive items prop, and render it. It also has ability to set the active item. For simplicity's sake, I render a button to set activeItem to the first one. The active item will also be rendered.

  function Menu({ items }) {
      const [activeItem, setActiveItem] = useState(items[0]);
      return (
        <div>
          {items}
          <hr />
          {activeItem}
        </div>
      );
    }

现在,进入主要部分:

  • I press the button (before hr) => it shows currentState (OK)
  • I press the active button (after hr) => it shows currentState (OK)
  • I press change state button => the state now changes to 1 (OK)
  • Now, if I press the button (before hr ) => It shows currentState is 1 (OK)
  • But, if I press the active button (after hr ) => It still shows 0 (which is the last state) (???)

My guess is React keeps remembering everything when using useState. But I'm not sure. Could anyone explain this for me!

我还提供了一些片段,以方便您理解我的问题。

const {useState} = React;
function Menu({ items }) {
  const [activeItem, setActiveItem] = useState(items[0]);
  return (
    <div>
      {items}
      <hr />
      <span>Active Item:</span>
      {activeItem}
    </div>
  );
}

function App() {
  const [state, setState] = useState(0);
  console.log(state);
  const onSelectItem = () => {
    console.log("🐞: onSelectItem -> currentState", state);
  };
  const items = ["FirstItem", "SecondItem"].map(item => {
    return (
      <button key={item} onClick={() => onSelectItem()}>
        {item}
      </button>
    );
  });
  return (
    <div className="App">
      <Menu items={items} />
      <hr />
      <button onClick={() => setState(prevState => prevState + 1)}>Change State</button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('app'));
<div id="app"></div>
<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>
<div id="react"></div>
回复