使用状态设置器作为带有反应钩子的道具

mgc*_*gcs 7 reactjs react-hooks

我试图了解从 useState 传递 setter 是否是一个问题。

在这个例子中,我的子组件同时接收状态和设置器来改变它。

export const Search = () => {
  const [keywords, setKeywords] = useState('');

  return (
    <Fragment>
      <KeywordFilter
        keywords={keywords}
        setKeywords={setKeywords}
      />
    </Fragment>
  );
};
Run Code Online (Sandbox Code Playgroud)

然后在孩子身上我有类似的东西:

export const KeywordFilter: ({ keywords, setKeywords }) => {

  const handleSearch = (newKeywords) => {
    setKeywords(newKeywords)
  };

  return (
    <div>
      <span>{keywords}</span>
      <input value={keywords} onChange={handleSearch} />
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

我的问题是,我应该在父级上有一个回调函数来 setKeywords 还是可以传递 setKeywords 并从子级调用它?

Nic*_*wer 8

不需要创建一个加法函数只是为了将值转发到 setKeywords,除非您想事先对这些值执行某些操作。例如,也许您担心子组件可能会向您发送错误数据,您可以这样做:

const [keywords, setKeywords] = useState('');

const gatedSetKeywords = useCallback((value) => {
  if (typeof value !== 'string') {
    console.error('Alex, you wrote another bug!');
    return;
  }
  setKeywords(value);
}, []);

// ...

<KeywordFilter
  keywords={keywords}
  setKeywords={gatedSetKeywords}
/>
Run Code Online (Sandbox Code Playgroud)

但大多数时候你不需要做类似的事情,所以传递 setKeywords 本身就可以了。