admin管理员组

文章数量:1327843

I started to use react-router and I find out that I can pass 'props' in Link ponent so some values can pass to another ponent. I'm sending a ponent called 'value' inside the button I'm using, however in the ponent that receive that parameter show an error message with the message 'Object is possibly null or undefined'.

Here is my code:

Where I'm sending the data:

<Container placeholder>
            <Segment>
            <Form>
                <Form.Field>
                    <label>Correo</label>
                    <input placeholder='Ingresa tu correo' name='nombre' onChange={actualizarUser}/>
                </Form.Field>
                <Form.Field>
                    <label>Contraseña</label>
                    <input placeholder='Ingresa tu contraseña' name='password' onChange={actualizarUser}/>
                </Form.Field>

                <Link to={{ pathname:'/init/home', state:{ value: token } }}> // Here I'm sending the props to the next ponent
                    <Button type='submit'>SubmitNuevo</Button>
                </Link>
                <Button type='submit' onClick={sendInfo}>Prueba</Button>
            </Form>
            </Segment>
        </Container>

And the ponent where I receive location.state

const Logged: React.FC<{}> = () => {

const [open, setOpen] = useState(false);  
const location = useLocation(); // Here I'm using useLocation to capture the props I sent
const [token, setToken] = useState('');

useEffect(() => {
        console.log(location.state);
        setToken(location.state.value); // Here is were I'm getting the error message
        console.log(token);
});

const handleOpen = () => {
    setOpen(true);
}

const handleClose = () => {
    setOpen(false);
}

return(<div>

    </div>
);

I also tried to manage that as props, however there's another error that show it as if location wasn't recognized:

Here is the information of the second option about where I'm using Route and props to pass the information

function App() {
  return (
    <div className="App">
      <Navbar bg="dark"  variant="dark">
        <Navbar.Brand href="#home">
          Micrin
        </Navbar.Brand>
    </Navbar>
    <Router>
        <Switch>
          <Route path='/login' ponent={InicioSesion} />
          <Route path='/register' ponent={Registro} />
          <Route path='/recover' ponent={RecuperarCuenta}/>
          <Route path='/init/home' exact ponent={Logged} />
          <Route path='/init/stock' exact ponent={Logged}  />
          <Route path='/init/menu' exact ponent={Logged} />
          <Route path='/init/sales' exact ponent={Logged} />
          <Route path='/init/market' exact ponent={Logged} />
          <Route path='/' ponent={MainPage} />
        </Switch>
    </Router>
    </div>
  );
}

And the ponent rendering with props I sent

const Logged: React.FC<{}> = (props) => {
    const [open, setOpen] = useState(false);  
    const [token, setToken] = useState('');

useEffect(() => {
        console.log(props.location.state);
        setToken(props.location.state.value); // Shows error message 'Property location does not exist on type {children?: ReactNode}'
        console.log(token);
});

const handleOpen = () => {
    setOpen(true);
}

const handleClose = () => {
    setOpen(false);
}

return(
    <div></div>
);

Thank you for your help

I started to use react-router and I find out that I can pass 'props' in Link ponent so some values can pass to another ponent. I'm sending a ponent called 'value' inside the button I'm using, however in the ponent that receive that parameter show an error message with the message 'Object is possibly null or undefined'.

Here is my code:

Where I'm sending the data:

<Container placeholder>
            <Segment>
            <Form>
                <Form.Field>
                    <label>Correo</label>
                    <input placeholder='Ingresa tu correo' name='nombre' onChange={actualizarUser}/>
                </Form.Field>
                <Form.Field>
                    <label>Contraseña</label>
                    <input placeholder='Ingresa tu contraseña' name='password' onChange={actualizarUser}/>
                </Form.Field>

                <Link to={{ pathname:'/init/home', state:{ value: token } }}> // Here I'm sending the props to the next ponent
                    <Button type='submit'>SubmitNuevo</Button>
                </Link>
                <Button type='submit' onClick={sendInfo}>Prueba</Button>
            </Form>
            </Segment>
        </Container>

And the ponent where I receive location.state

const Logged: React.FC<{}> = () => {

const [open, setOpen] = useState(false);  
const location = useLocation(); // Here I'm using useLocation to capture the props I sent
const [token, setToken] = useState('');

useEffect(() => {
        console.log(location.state);
        setToken(location.state.value); // Here is were I'm getting the error message
        console.log(token);
});

const handleOpen = () => {
    setOpen(true);
}

const handleClose = () => {
    setOpen(false);
}

return(<div>

    </div>
);

I also tried to manage that as props, however there's another error that show it as if location wasn't recognized:

Here is the information of the second option about where I'm using Route and props to pass the information

function App() {
  return (
    <div className="App">
      <Navbar bg="dark"  variant="dark">
        <Navbar.Brand href="#home">
          Micrin
        </Navbar.Brand>
    </Navbar>
    <Router>
        <Switch>
          <Route path='/login' ponent={InicioSesion} />
          <Route path='/register' ponent={Registro} />
          <Route path='/recover' ponent={RecuperarCuenta}/>
          <Route path='/init/home' exact ponent={Logged} />
          <Route path='/init/stock' exact ponent={Logged}  />
          <Route path='/init/menu' exact ponent={Logged} />
          <Route path='/init/sales' exact ponent={Logged} />
          <Route path='/init/market' exact ponent={Logged} />
          <Route path='/' ponent={MainPage} />
        </Switch>
    </Router>
    </div>
  );
}

And the ponent rendering with props I sent

const Logged: React.FC<{}> = (props) => {
    const [open, setOpen] = useState(false);  
    const [token, setToken] = useState('');

useEffect(() => {
        console.log(props.location.state);
        setToken(props.location.state.value); // Shows error message 'Property location does not exist on type {children?: ReactNode}'
        console.log(token);
});

const handleOpen = () => {
    setOpen(true);
}

const handleClose = () => {
    setOpen(false);
}

return(
    <div></div>
);

Thank you for your help

Share edited May 16, 2020 at 10:35 Hugo 1,08415 silver badges26 bronze badges asked May 15, 2020 at 20:51 Andrés F Ariza CalderónAndrés F Ariza Calderón 2353 gold badges9 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

The second error you are getting is a Typescript error. It occurs because Typescript is not aware of the interface of your props.

When you define your ponent, you tell Typescript it is a React Functional ponent by writing:

const Logged: React.FC<{}>

Logged is a variable of type React.FC. The React.FC is a generic type. It means it can take an argument. This argument is the type of props your ponent accepts.

Here, you are telling Typescript that your ponent accepts no props at all: React.FC<{}>. So Typescript expect Logged to be basic React functional ponent (so it accepts only, eventually some children).

This is why Typescript plains when you try to get location from the props: Typescript doesn't expect to have such a prop:

You need to tell Typescript that this ponent accepts a location prop. You can do it by creating an interface like this:

interface Props {
  // your props here
  location;
}

const Logged: React.FC<Props> = ({ location }) => {
  // your code
}

(note: I also used props destructuring because I think it makes the code cleaner, but feel free to use props directly into your ponent)

But here, I just told Typescript there is a location variable, but I didn't explicitly set its type.

In your case, it is a bit more tricky because React Router is injecting these props for you. So in this case you can extend your Props interface like this:

import React, { useEffect, useState } from 'react';

import { StaticContext } from 'react-router';
import { RouteComponentProps } from 'react-router-dom';

type LocationState = {
  value: string;
};

interface Props extends RouteComponentProps<{}, StaticContext, LocationState> {
  // Here you can define the other props of your ponent
  // if needed
}

const Logged: React.FC<Props> = ({ location }) => {
  const [open, setOpen] = useState(false);
  const [token, setToken] = useState('');

  useEffect(() => {
    setToken(location.state.value);
  });

  return <div>Hello</div>;
};

export default Logged;

And now, because Typescript is aware of the type of your props, your IDE can also auto-plete:

and it knows value is a string:

I suggest you to take a look at this SO question: React Typescript: add location state to react router ponent

and to some "intro to typescript + react" tutorials such as this one: https://alligator.io/react/typescript-with-react/

Because you will get a lot of errors like this and when you know how to read them, it is not super hard to solve.

I think your first error is also related to some missing types but I could not understand the exact problem and reason with what you shared here.

本文标签: javascriptuseLocation doesn39t recognize stateStack Overflow