设置输入初始值并使用钩子更新 onChange。错误:渲染的钩子比上一次渲染时更多

时间:2021-02-19 19:25:50

标签: reactjs react-hooks

我看过其他类似的问题,但似乎无法弄清楚。我知道钩子,我们想把它们放在组件的顶部,应该避免把它们放在条件中,但我不确定我哪里出错了。任何见解都将不胜感激,因为我在这方面花费了令人尴尬的大量时间。彻底的大脑崩溃。非常感谢。

我正在使用 getData 设置输入的初始值,而 onChange 需要调用 setData 的钩子来更新每个输入。它最初有效,然后在以后的重新渲染时爆炸。

const createCustomInputAttrBlock = (
  productId: any, 
  customAttributeName: string, 
  customData: any) => {

  const [getData, setData] = React.useState(customData);

  if (customAttributeName === 'customunits') {
    return (
      <styles.ProductTableCellBorderRight>
        <styles.ProductInputField
          component="bs-input"
          type="input"
          class="product-input-field"
          key={`product-${productId}`}
          name={`product-${productId}`}
          value={getData === '0.0' ? null : getData}
          onChange={(e) => setData(utils.allowDollarChars(e.target.value))}
          />
      </styles.ProductTableCellBorderRight>
    );
  } else {
    return (
      <styles.ProductTableCell>
        <styles.ProductInputField
          component="bs-input"
          type="input"
          class="product-input-field"
          key={`product-${productId}`}
          name={`product-${productId}`}
          value={getData === '0.0' ? null : getData}
          onChange={(e) => setData(utils.allowDollarChars(e.target.value))}
          />
      </styles.ProductTableCell>
    );
  }
};

这仅在文件更下方的此处被调用:

      <styles.ProductCardDiv colSpan={2} style={{ width: '100%' }}>
        {customAttributes === 'customunits' ? (
          createCustomInputAttrBlock(productId, customAttributes, customData)
        ) : (
            <div>Result 1</div>
          )}

        {customAttributes === 'custompoints' ? (
          createCustomInputAttrBlock(productId, customAttributes, customData)
        ) : (
            <div>Result 2</div>
          )}
      </styles.ProductCardDiv>
    </div>```

0 个答案:

没有答案