Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

249
Vistas
No se muestra el valor del estado importado del enlace personalizado

Creé un enlace personalizado, Custom.js:

 import React, {useState, useEffect} from 'react'; import Clarifai from 'clarifai'; const app = new Clarifai.App({ apiKey: 'XXXXXXXXXXXXXX' }) const Custom = () => { const [input, setInput] = useState(''); const [imgUrl, setImgUrl] = useState(''); function onInputChange (text) { setInput(text); } useEffect(()=>{ setImgUrl(input) }, [input]) function onSubmit () { console.log('submitted'); console.log(imgUrl) app.models.predict(Clarifai.COLOR_MODEL, "https://www.takemefishing.org/getmedia/bde1c54e-3a5f-4aa3-af1f-f2b99cd6f38d/best-fishing-times-facebook.jpg?width=1200&height=630&ext=.jpg").then( function(response) { console.log(response); }, function(err) { // there was an error } ); } return {input, imgUrl, onInputChange, onSubmit} } export default Custom;

Importé este gancho personalizado en 2 de mis otros componentes, FaceRecognition.js y InputForm.js.

FaceRecognition.js:

 import React from 'react'; import Custom from '../Custom'; const FaceRecognition = () => { const { imgUrl } = Custom(); function yes (){ return console.log(imgUrl) } yes() return ( <div> <h1 className='white'>The url is {ImgUrl} </h1> <img width={'50%'} alt=''src={imgUrl}/> </div> ); } export default FaceRecognition;

ImportForm.js:

 import React, {useState} from 'react'; import './InputForm.css' import Custom from '../Custom'; const InputForm = () => { const { onInputChange, onSubmit } = Custom(); return ( <> <p className='txt f3'>Enter image link address</p> <div className='center flex w-70'> <input type='text' className='w-80 pa1' onChange={(e)=>onInputChange(e.target.value)}/> <button className='w-20 pa1 pointer' onClick={onSubmit}>Detect</button> </div> </> ); } export default InputForm;

Las funciones onSubmit y onImputChange funcionan como se esperaba para InputForm.js y el valor de imgUrl registra en la consola cuando se ejecuta la función onSubmit , como se esperaba. Pero el estado de imgUrl , que es una cadena, no aparece entre las etiquetas h1 <h1 className='white'>The url is {imgUrl} boy</h1> de mi fragmento FaceRecognition.js anterior, y tampoco funciona como el src de la imagen <img width={'50%'} alt=''src={imgUrl}/> debajo de la etiqueta h1. Este es mi problema.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Tema

Los ganchos de reacción no comparten el estado mágicamente. Tiene dos instancias separadas de esta función Custom , cada una con su propio useState . Digo "función" porque también nombraste mal tu gancho. Todos los hooks de React deben nombrarse con un prefijo "use-" para que React pueda identificarlos y aplicar las Reglas de Hooks en su contra.

Solución

Si desea instancias separadas de su useCustom para compartir el estado, entonces el estado debe elevarse a un componente común para compartir. Para esto debes usar un React Context.

Ejemplo:

 import React, { createContext, useContext, useState, useEffect } from 'react'; import Clarifai from 'clarifai'; const app = new Clarifai.App({ apiKey: 'XXXXXXXXX' }); const CustomContext = createContext({ input: '', imgUrl: '', onInputChange: () => {}, onSubmit: () => {} }); const useCustom = () => useContext(CustomContext); const CustomProvider = ({ children }) => { const [input, setInput] = useState(''); const [imgUrl, setImgUrl] = useState(''); function onInputChange (text) { setInput(text); } useEffect(()=>{ setImgUrl(input); }, [input]); function onSubmit () { console.log('submitted'); console.log(imgUrl); app.models.predict( Clarifai.COLOR_MODEL, "https://www.takemefishing.org/getmedia/bde1c54e-3a5f-4aa3-af1f-f2b99cd6f38d/best-fishing-times-facebook.jpg?width=1200&height=630&ext=.jpg" ).then( function(response) { console.log(response); }, function(err) { // there was an error } ); } return ( <CustomContext.Provider value={{ input, imgUrl, onInputChange, onSubmit }}> {children} </CustomContext.Provider> ); } export { CustomContext, useCustom }; export default CustomProvider;

Uso:

Envuelva su aplicación con su componente CustomProvider .

 import CustomProvider from '../path/to/CustomProvider'; ... return ( <CustomProvider> <App /> </CustomProvider> );

Importe y use el useCustom en los consumidores.

 import React from 'react'; import { useCustom } from '../path/to/CustomProvider'; const FaceRecognition = () => { const { imgUrl } = useCustom(); useEffect(() => { console.log(imgUrl); }); return ( <div> <h1 className='white'>The url is {ImgUrl}</h1> <img width={'50%'} alt='' src={imgUrl}/> </div> ); } export default FaceRecognition;

...

 import React, {useState} from 'react'; import './InputForm.css' import { useCustom } from '../path/to/CustomProvider'; const InputForm = () => { const { onInputChange, onSubmit } = useCustom(); return ( <> <p className='txt f3'>Enter image link address</p> <div className='center flex w-70'> <input type='text' className='w-80 pa1' onChange={(e) => onInputChange(e.target.value)} /> <button className='w-20 pa1 pointer' onClick={onSubmit} > Detect </button> </div> </> ); } export default InputForm;
about 4 years ago · Juan Pablo Isaza Denunciar

0

intente poner su declaración de devolución dentro del .then de la predicción

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda