Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - Conditional routing based on boolean variable

I having problem with this line:

<Route path="/" render={() => isReg ? <Registro />: <Home /> } />

What I get is this:

JSX element type 'Element | undefined' is not a constructor function for JSX elements. Type 'undefined' is not assignable to type 'Element | null'. TS2605

What I want to do is corroborate if the user has registered with isReg variable, in case if it has been registered, "/home" must be displayed, otherwise "/Registro"

But I can't fix that conditional routing statement. I would appreciate a lot of help. Thanks in advance.

const App: React.FC = () => {
  const [isReg, setIsReg] = useState(false);

  useEffect(() => {
    if(getItem("isRegistered2")==null){
    console.log(getItem("isRegistered2"));
    setIsReg(true);
  }
  else{
    setIsReg(false);
  }
}, []);

return(
<IonApp>
<IonReactRouter>
<IonSplitPane contentId="main" when="(min-width: 4096px)">
      <Menu />
  <IonRouterOutlet id="main">
  <Route path="/" render={() => isReg ? <Registro />: <Home /> } />
    <Route path="/registro" component={Registro} exact={true}></Route>
    <Route path="/ingresar" component={Ingresar} exact={true}></Route>
    <Route path="/MisServicios" component={MisServicios} exact={true}></Route>
    <Route path="/Favoritos" component={Favoritos} exact={true}></Route>
    <Route path="/HistorialServicios" component={HistorialServicios} exact={true}></Route>
    <Route path="/Completarinfo" component={Completarinfo} exact={true} />
    <Route path="/Login" component={Login} exact={true} />


    <Route path="/tab2" component={Tab2} exact={true} />



  </IonRouterOutlet>
  </IonSplitPane>
</IonReactRouter>
</IonApp>

);
};

export default App; 

Inglés

I think the problem lies in the Home component. Since if I change home for another component I have no problems. What I see differently in Home is that it has a Modal.

Home.tsx

const Home = () => {
  const [showModal, setShowModal] = useState({ isOpen: false });
  const [retVal, setRetVal] = useState(null);
  const [count, setCount] = useState(0);

  const [login, setLogin]=useState(0);

  const axios = require('axios');

  const data2 = getLocation();

  if(getItem("isRegistered")!=null){
    console.log(getItem("isRegistered"));
    setLogin(1);
  }
  else{
    setLogin(0);
  }

  data2.then((value)=>{
    
    console.log(url+value);
    axios.get(url+value).then((resp: { data: any; }) => {

      console.log(resp.data);
    });  
  
  })
  
  if(login===1){
    return (
      <IonPage>
        <IonHeader>
          <IonToolbar>
            <IonGrid>
              <IonRow id="header">
                <IonCol id="columna" size="1.5"><IonButtons ><IonMenuButton /> </IonButtons></IonCol>
                <IonCol id="columna2" ><Busqueda /></IonCol>
                <IonCol id="columna3" size="2"> 
                  <IonChip  onClick={() => {  setShowModal({ isOpen: true});  setCount(0)}}id="user" >
                    <IonIcon icon={person} id="foto-usuario"/>
                  </IonChip>
                 </IonCol>
              </IonRow>
            </IonGrid>
          </IonToolbar>
        </IonHeader>
        
        <IonContent className="ion-padding">
        <IonModal
            animated={true}
            isOpen={showModal.isOpen}
            onDidDismiss={() => setShowModal({ isOpen: false })}
          >
            <MyModal 
               tipo={count}
               onClose={(value: React.SetStateAction<null>) => {
                setShowModal({ isOpen: false });
                value ? setRetVal(value) : setRetVal(null);
              }} 
            />  
          </IonModal>

          <IonGrid>
          <IonRow>
          <IonCol>
            <div id="contenedor-prueba">
            <IonChip className="boton-generales"  onClick={() => {  setShowModal({ isOpen: true});  setCount(1)}}>
              <IonLabel ><small>Emergencias</small></IonLabel>
              <IonAvatar> <img src={"./assets/icon/sirena.png"} className="imagen-boton-principal"/></IonAvatar> 
            </IonChip>
            </div>
          </IonCol>
          <IonCol>
          <div id="contenedor-prueba">
            <IonChip className="boton-generales"  onClick={() => {  setShowModal({ isOpen: true});  setCount(2)}}>
              <IonLabel><small>Categorías</small></IonLabel>
              <IonAvatar> <img src={"./assets/icon/servicio.png"} className="imagen-boton-principal"/></IonAvatar> 
            </IonChip>
            </div>
          </IonCol>
          <IonCol>
          <div id="contenedor-prueba">
            <IonChip className="boton-generales"  onClick={() => {  setShowModal({ isOpen: true});  setCount(3)}}>
              <IonLabel><small>Programado</small></IonLabel>
              <IonAvatar> <img src={"./assets/icon/time.png"} className="imagen-boton-principal"/></IonAvatar> 
            </IonChip>
            </div>
          </IonCol>
          </IonRow>
          </IonGrid>

          <ExploreContainer  />
        </IonContent>
      </IonPage>
  );

  }
  
};


const MyModal: React.FC<{onClose: any; tipo: number;}> = ({ onClose, tipo }) => {
  
  if(tipo===0){
    return (
      <>
      <IonHeader>
        <IonToolbar>
        <IonIcon icon={arrowBack} onClick={() => onClose(null)} slot="start" id="flecha-volver">  </IonIcon>

        </IonToolbar>
      </IonHeader>
      <IonContent>
        <div id="contenedor-central">
          <br></br>
          <IonButton href="/ingresar" id="botoningresoregistro">INGRESAR</IonButton>
          <IonButton href="/registro" id="botoningresoregistro">REGISTRARSE</IonButton>
        </div>
      </IonContent>
    </>
    );
  }
  if(tipo===1){
    return (
      <>
      <IonHeader>
        <IonToolbar>
        <IonIcon icon={arrowBack} onClick={() => onClose(null)} slot="start" id="flecha-volver">  </IonIcon>

        </IonToolbar>
      </IonHeader>
      <IonContent>
        <div id="contenedor-central">
          <strong>Emergencias</strong>
        </div>
      </IonContent>
    </>
    );
  }
  if(tipo===2){
    return (
      <>
      <IonHeader>
        <IonToolbar>
        <IonIcon icon={arrowBack} onClick={() => onClose(null)} slot="start" id="flecha-volver">  </IonIcon>

        </IonToolbar>
      </IonHeader>
      <IonContent>
        <div id="contenedor-central">
          <strong>Categorías</strong>
        </div>
      </IonContent>
    </>
    );
  }
  else{
    return (
      <>
      <IonHeader>
        <IonToolbar>
        <IonIcon icon={arrowBack} onClick={() => onClose(null)} slot="start" id="flecha-volver">  </IonIcon>

        </IonToolbar>
      </IonHeader>
      <IonContent>
        <div id="contenedor-central">
          <strong>Programados</strong>
        </div>
      </IonContent>
    </>
    );
  }
 
};


class Modal extends Component{
  constructor(props: Readonly<{}>) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log('Se hizo click');
  }
  render() {
    return <button onClick={this.handleClick}>Clickéame</button>;
  }
}


class Busqueda extends Component{

  Buscar = () =>{
    var input=(document.getElementById("busqueda") as HTMLTextAreaElement).value;
  
    if(input==="hola"){
      console.log("hola perri");
    }
  }
   render(){
    return(<IonSearchbar type="text" placeholder="?Qué servicios buscas?" onIonInput={this.Buscar} id="busqueda"></IonSearchbar>);
       }
    
  };

  export default Home;
question from:https://stackoverflow.com/questions/65851912/conditional-routing-based-on-boolean-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Define a new component that handles the conditional rendering. The isReg state should not lie inside App.js.

AppReg.js

const AppReg: React.FC = () => {
  const [isReg, setIsReg] = useState(null);

  useEffect(() => {
    if (getItem('isRegistered2') == null) {
      console.log(getItem('isRegistered2'));
      setIsReg(true);
    } else {
      setIsReg(false);
    }
  }, []);

  if (isReg == null) {
    return <Loader />;
  }

  if (isReg === true) {
    return <Registro />;
  } else {
    return <Home />;
  }
};

export default AppReg;

App.js

const App: React.FC = () => {
  return (
    <IonApp>
      <IonReactRouter>
        <IonSplitPane contentId="main" when="(min-width: 4096px)">
          <Menu />
          <IonRouterOutlet id="main">
            <Route path="/" component={AppReg} />
            <Route path="/registro" component={Registro} exact={true}></Route>
            <Route path="/ingresar" component={Ingresar} exact={true}></Route>
            <Route path="/MisServicios" component={MisServicios} exact={true}></Route>
            <Route path="/Favoritos" component={Favoritos} exact={true}></Route>
            <Route path="/HistorialServicios" component={HistorialServicios} exact={true}></Route>
            <Route path="/Completarinfo" component={Completarinfo} exact={true} />
            <Route path="/Login" component={Login} exact={true} />

            <Route path="/tab2" component={Tab2} exact={true} />
          </IonRouterOutlet>
        </IonSplitPane>
      </IonReactRouter>
    </IonApp>
  );
};

export default App;

Update: The Home component needs to return null for the default case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...