Soy nuevo en los componentes funcionales después de pasar mucho tiempo con los componentes de clase. Mientras probaba algo, me encontré con algunos problemas. Cómo usar componentWillReceiveProps
en el contexto del gancho useEffect
,
componentWillReceiveProps(nextProps) { if (_.isEmpty(nextProps.user)) { this.props.history.push("/signin"); } this.setState({ selImg: nextProps.meetingData.themeImage, }); }
Envuelva el efecto secundario de cambiar la ruta en un useEffect()
, y hágalo dependiente del user
, para que reaccione cada vez que user
cambie. También necesita el history
como una dependencia, pero no cambiaría.
Asigne meetingData.themeImage
a una const
o utilícelo directamente, ya que el componente se volverá a representar de todos modos si cambia.
const Example = ({ user, history, meetingData }) => { useEffect(() => { if (_.isEmpty(user)) { history.push("/signin"); } }, [user, history]); const selImg = meetingData.themeImage; return ( // JSX ); }
Esto podría ser equivalente a useEffect
con dependencia en el componente funcional:
useEffect(() => { if (_.isEmpty(props.user)) { props.history.push("/signin"); } setState({ selImg: props.meetingData.themeImage, }); }, [props.user]);
A continuación se muestra la implementación funcional de su código.
En lugar de setState
, puede usar useState
, en lugar de componentWillReceiveProps
, puede escuchar actualizaciones de variables usando useEffect
.
Tenga en cuenta el segundo argumento de useEffect
, la matriz de dependencias. Allí puede elegir qué actualizaciones activarán la primera variable de useEffect
(es decir, la devolución de llamada).
function FunctionalImplementation({ user, history, meetingData }) { // The functional equivalent of `this.state = { selImg: null }` const [selImg, setSelImg] = useState(null); useEffect(() => { if (_.isEmpty(user)) { history.push("/signin"); } // You might want to put this inside an `else` block, just to be more clear setSelImg(meetingData.themeImage); // If you want to update `selImg` when `props.meetingData` changes too, // add it to useEffect's dependencies array }, [user, history]); }