繁体   English   中英

useLocation 无法识别我发送的 state

[英]useLocation doesn't recognize the state I sent

我开始使用 react-router 并发现我可以在 Link 组件中传递“props”,因此一些值可以传递给另一个组件。 我正在使用的按钮内发送一个名为“值”的组件,但是在接收该参数的组件中显示一条错误消息,消息为“对象可能是 null 或未定义”。

这是我的代码:

我在哪里发送数据:

<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 component
                    <Button type='submit'>SubmitNuevo</Button>
                </Link>
                <Button type='submit' onClick={sendInfo}>Prueba</Button>
            </Form>
            </Segment>
        </Container>

以及我收到 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>
);

谢谢您的帮助

您需要使用props.location而不是useLocation(); . 你能试试这个。

 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); // Here is were I'm getting the error message console.log(token); }); const handleOpen = () => { setOpen(true); } const handleClose = () => { setOpen(false); } return(<div> </div> );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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