30秒学会 React 片段 · 2023年7月2日

30秒学会 React 片段 – React useDefault hook

Creates a stateful value with a default fallback if it’s null or undefined, and a function to update it.

  • Use the useState() hook to create stateful value.
  • Check if the value is either null or undefined.
  • Return the defaultState if it is, otherwise return the actual value state, alongside the setValue function.

代码实现

const useDefault = (defaultState, initialState) => {
  const [value, setValue] = React.useState(initialState);
  const isValueEmpty = value === undefined || value === null;
  return [isValueEmpty ? defaultState : value, setValue];
};

使用样例

const UserCard = () => {
  const [user, setUser] = useDefault({ name: 'Adam' }, { name: 'John' });

  return (
    <>
      <div>User: {user.name}</div>
      <input onChange={e => setUser({ name: e.target.value })} />
      <button onClick={() => setUser(null)}>Clear</button>
    </>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <UserCard />
);

翻译自:https://www.30secondsofcode.org/react/s/use-default