简体   繁体   English

useState 初始值未设置

[英]useState initial value is not set

Following is a simplified version of my requirement that is just enough to recreate the issue.以下是我的要求的简化版本,足以重新创建问题。 Component ColorBox receives a prop from ShowColorComponent that is used to set the initial value of ColorBox.visible state.组件ColorBoxShowColorComponent接收一个 prop,用于设置ColorBox.visible state 的初始值。

import React, { useState } from "react";

export const Container = ({ Component }) => {
  return (
    <>
      <Component />
    </>
  );
};

export const ShowColorComponent = () => {
  const [isVisible, setIsVisible] = useState(false);

  const handleClick = () => {
    setIsVisible(!isVisible);
  };

  return (
    <>
      <button onClick={handleClick}>click</button>
      <ColorBox isVisible={isVisible} />
    </>
  );
};

export const ColorBox = ({ isVisible }) => {
  const [visible, setVisible] = useState(isVisible);

  console.log(visible);
  console.log(isVisible);

  return (
    <div
      style={{
        widht: "50px",
        height: "50px",
        backgroundColor: "red",
        display: `${visible ? "block" : "none"}`
      }}
    ></div>
  );
};

App.js应用程序.js

import React from "react";
import ReactDOM from "react-dom";
import { Component, ShowColorComponent } from "./demo";

ReactDOM.render(
  <Component ShowColorComponent={ShowColorComponent} />,
  document.querySelector("#root")
);

I probably should use a method to set the parent's ShowColorComponent.isVisible instead of redefining new state new in ColorBox .我可能应该使用一种方法来设置父级的ShowColorComponent.isVisible而不是在 ColorBox 中重新定义新的ColorBox new 。 But why the first time I click on the button, outputs of console.log s shows following?但是为什么我第一次单击按钮时, console.log的输出显示如下?

false
true

Since I'm setting value of isVisible as the initial value, how visible is false?由于我将isVisible的值设置为初始值,因此visible性如何?

Here is the CodeSandbox example https://codesandbox.io/s/react-state-issue-sc58k这是 CodeSandbox 示例https://codesandbox.io/s/react-state-issue-sc58k

If your question is why the visible and isVisible are different, that is because the useState runs only the first time the React component is rendered.如果你的问题是为什么visibleisVisible不同,那是因为 useState 只在 React 组件第一次渲染时运行。 (Until it is unmounted and mounted again). (直到它被卸载并再次安装)。

If you want to track the change to any variable every time it changes, use the useEffect hook, as in:如果您想在每次更改时跟踪对任何变量的更改,请使用 useEffect 挂钩,如下所示:

useEffect(() => {
    setVisible(isVisible);
  }, [isVisible]);

In your case, you can just delete the const [visible, setVisible] = useState(isVisible);在您的情况下,您可以删除const [visible, setVisible] = useState(isVisible); line and use your parent's isVisible in your display:行并在显示中使用您父母的 isVisible :

display: `${isVisible ? "block" : "none"}`

or not even render the div at all with the && operator.甚至根本不使用 && 运算符渲染 div。

return (
    isVisible &&
    <div
      style={{
        widht: "50px",
        height: "50px",
        backgroundColor: "red"
      }}
    ></div>
  );

When you render ColorBox isVisible is false which also makes visible false as well.当您渲染ColorBox isVisiblefalse时,它也会使visiblefalse But when you click, it doesn't call setVisible .但是当您单击时,它不会调用setVisible So visible is still false , but the click did call setIsVisible which turned isVisible to true .所以visible仍然是false ,但是点击确实调用setIsVisible ,它把isVisible变成了true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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