【问题标题】:why state is not initializing with given value?为什么状态没有用给定的值初始化?
【发布时间】:2021-12-02 13:26:14
【问题描述】:

最新值来自 props,但是当它作为 state 的初始值添加时,它没有显示出来。

 import React, { useRef, useState } from "react";
 //import config from "../../../../../../config";
 //import { getAuthToken } from "../../../../../utils/auth";
 import styles from "./ContentRowPrice.module.css";

 const ContentRowPrice = (props) => {
   const [priceInput, setPriceInput] = useState(props.price);
   // const priceInput = useRef();

   // const handleBlur = () => {
   //   const price = parseFloat(priceInput.current.value);
   //   if (props.price === price) {
   //   } else {
   //     props.onPaywallChange(price);
   //   }
   // };

    const classes = styles["contentrowprice-input"];
    return (
      <>
        <span>{props.price}</span>
        <span>{priceInput}</span>
        <input
          id={`paywall_${props.price}_${props.id}`}
          type="number"
          min="0"
          step="0.01"
          // ref={priceInput}
          // defaultValue={props.price}
          value={priceInput}
          className={classes}
          // onBlur={handleBlur}
        />
    </>
  );
};
export default ContentRowPrice;

我意识到值 10 实际上来自之前代替上述输入的输入。

【问题讨论】:

  • 您能分享一下渲染ContentRowPrice 并传递price 属性值的内容吗?我怀疑有一些异步逻辑在起作用,price 不是您在安装ContentRowPrice 组件时所期望的值。您能否也澄清一下“未出现”的确切含义?
  • 在 React 中将传递的 props 存储在本地状态中通常也被认为是反模式。你能解释一下用例吗?
  • 是的,我刚刚意识到,如果我传递道具,我不需要本地状态。我很抱歉。

标签: html reactjs web react-hooks


【解决方案1】:

React 组件的第一次渲染是空值,这是 React 组件创建组件和带有useState 钩子的状态的时刻。

当您在useState 中分配它时,它不会在没有useEffect 钩子的情况下在第二次(或以后)重新渲染中发生变化。

  useEffect(() => {
   setPriceInput(props.price);
  }, [props.price]);

有关此问题的更多信息,您可以在此处阅读: https://medium.com/@digruby/do-not-use-props-as-default-value-of-react-usestate-directly-818ee192f454

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 2023-01-01
    • 2015-02-20
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2011-02-02
    相关资源
    最近更新 更多