在函数组件中使用 useState hook 的最佳方式?

Müc*_*nel 1 javascript reactjs react-hooks use-state

我想显示一个与对象属性相关的 div,该属性为 true 或 false。我使用了一种方法,但我不确定这是最好的方法,或者它是否会带来性能问题。

我正在循环中检查返回部分的属性,以避免额外的数组操作。但我认为这会导致额外的渲染。

另一个选项是从返回部分外部检查该属性。但这会导致额外的数组操作。

哪种方式最适合我?我在下面展示了两种不同的实现。

选项1:

const RadioButtonList: FunctionComponent<RadioButtonListProps> = ({ items, changeFilter }) => {
  const [showClearIcon, setShowClearIcon] = React.useState(false);
  
  return (
    <div className="radio-button-list">
      {showClearIcon && <div className="clear-icon">clear</div>}
      <ul>
        {items.map(item => {
          /* this is the area what I'm checking the property */
          if (item.selected) {
            setShowClearIcon(true);
          }
          return (
            <li key={item.id}>
              <label htmlFor={item.text} className="radio">
                <span className="input">
                  <input type="radio" onClick={changeFilter} readOnly />
                </span>
              </label>
            </li>
          );
        })}
      </ul>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

选项2:

const RadioButtonList: FunctionComponent<RadioButtonListProps> = ({ items, changeFilter }) => {
  const [showClearIcon, setShowClearIcon] = React.useState(false);


  /* set in useEffect hook */
  useEffect(() => {
    if(items.some(item => item.selected)) {
      setShowClearIcon(true);
    }
  }, [items]);
  
  return (
    <div className="radio-button-list">
      {showClearIcon && <div className="clear-icon">clear</div>}
      <ul>
        {items.map(item => {
          return (
            <li key={item.id}>
              <label htmlFor={item.text} className="radio">
                <span className="input">
                  <input type="radio" onClick={changeFilter} readOnly />
                </span>
              </label>
            </li>
          );
        })}
      </ul>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

AKX*_*AKX 6

看起来根本showClearIcon不需要是一个状态原子,而只是一个依赖于的记忆值items

const showClearIcon = React.useMemo(
  () => items.some(item => item.selected), 
  [items],
);
Run Code Online (Sandbox Code Playgroud)