简体   繁体   中英

Is it bad practice to accept setState as a function parameter in React?

Basically, before uploading an image to the firebase, I'm trying to control the input as:

export const controlThumbnail = (selectedThumbnail, setThumbnailError) => {
  if (!selectedThumbnail) {
    setThumbnailError('Please select a thumbnail!');

    return;
  }

  if (!selectedThumbnail.type.includes('image')) {
    setThumbnailError('Please select an image!');

    return;
  }

  if (selectedThumbnail.size > 1000000) {
    setThumbnailError('Image size must be less than 1MB!');

    return;
  }

  setThumbnailError(null);
};

which I call the above method from /lib/controlThumbnail.js to:

import { controlThumbnail } from '../../lib/controlThumbnail';
    
const Signup = () => {
  const [userInfo, setUserInfo] = useState({
    name: '',
    email: '',
    password: '',
    thumbnail: null
  });
  const [thumbnailError, setThumbnailError] = useState(null);


  const userInputHandler = (e) => {
    setUserInfo((prevUserInfo) => {
      if (e.target.name === 'thumbnail') {
        const thumbnail = e.target.files[0];
        controlThumbnail(thumbnail, setThumbnailError);

        return { ...prevUserInfo, thumbnail };
      } else {
        return { ...prevUserInfo, [e.target.name]: e.target.value };
      }
    });
  };
...

so, this is now works correctly, but I wonder if this is the good way of doing it? Or should I put the control method inside the component and never give setState as parameter?

It is subjective. Personally, I think the controlThumbnail function is not the right place to make that abstraction. In here, you are really only providing validation. You don't need to give it the responsibility to validate AND set some state.

You could create a pure validation function, and just use the return of this to update the state in your Signup component:

const validateThumbnail = (thumbnail) => {
  if (!thumbnail) {
    return 'Please select a thumbnail!';
  }

  if (!thumbnail.type.includes('image')) {
    return 'Please select an image!'
  }

  if (thumbnail.size > 1000000) {
    return 'Image size must be less than 1MB!'
  }

  return null
}

const Signup = () => {
  const [userInfo, setUserInfo] = useState({
    name: '',
    email: '',
    password: '',
    thumbnail: null
  });
  const [thumbnailError, setThumbnailError] = useState(null);


  const userInputHandler = (e) => {
    setUserInfo((prevUserInfo) => {
      if (e.target.name === 'thumbnail') {
        const thumbnail = e.target.files[0];
        setThumbnailError(validateThumbnail(thumbnail));
        return { ...prevUserInfo, thumbnail };
      }
      return { ...prevUserInfo, [e.target.name]: e.target.value };
    });
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM