【问题标题】:Can I use ReactElement as useState argument?我可以使用 ReactElement 作为 useState 参数吗?
【发布时间】:2021-08-06 13:51:49
【问题描述】:

我是 React 的新手,我想知道使用 ReactElement 作为 useState 参数是否正常? 我试着去做,一切都很好。是反模式还是没问题? 不幸的是,我在文档中没有找到任何有关它的信息

const [infoBox, setInfobox] = useState<ReactElement|null>(null);
const catalogLoadedDataEmpty = useSelector(getCatalogLoadedDataEmptySelector);
const catalogHasErrors = useSelector(getCatalogHasErrorsSelector);
...
useEffect(() => {
    let infoBoxTitle;

    if (catalogLoadedDataEmpty) {
      infoBoxTitle = t('pages.Brands.errors.noResults.title');
    } else if (catalogHasErrors) {
      infoBoxTitle = errorsByErrorCode[EErrorCodes.UNRECOGNIZED_ERROR](t);
    } else {
      setInfobox(null);
      return;
    }

    setInfobox(<InfoBox
      className={catalogInfoBoxClassname}
      iconName={EInfoBoxIcon.error}
      title={infoBoxTitle}
      description={noResultsDescription}
    />);
}, [catalogLoadedDataEmpty, catalogHasErrors]);

【问题讨论】:

    标签: reactjs use-state


    【解决方案1】:

    您可以,但很容易在您希望页面更新的地方创建错误,但事实并非如此,因为您忘记更新状态。通常最好将数据保存在 state 中,然后在每次渲染时使用该数据渲染新元素。

    在你的情况下,我会更进一步:这根本不应该是一个状态变量。 catalogLoadedDataEmptycatalogHasErrors 的值足以直接确定所需的输出。因此,您可以删除使用效果,从而摆脱您当前拥有的双重渲染:

    const catalogLoadedDataEmpty = useSelector(getCatalogLoadedDataEmptySelector);
    const catalogHasErrors = useSelector(getCatalogHasErrorsSelector);
    
    let infoBoxTitle;
    if (catalogLoadedDataEmpty) {
      infoBoxTitle = t('pages.Brands.errors.noResults.title');
    } else if (catalogHasErrors) {
      infoBoxTitle = errorsByErrorCode[EErrorCodes.UNRECOGNIZED_ERROR](t);
    }
    
    const infoBox = infoBoxTitle ? (
      <InfoBox
        className={catalogInfoBoxClassname}
        iconName={EInfoBoxIcon.error}
        title={infoBoxTitle}
        description={noResultsDescription}
      />
    ) : null
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 2020-02-09
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 2015-12-01
      • 2013-09-20
      相关资源
      最近更新 更多