【问题标题】:useLocation doesn't recognize the state I sentuseLocation 无法识别我发送的状态
【发布时间】:2020-05-15 04:51:05
【问题描述】:

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

这是我的代码:

我将数据发送到哪里:

<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>
);

感谢您的帮助

【问题讨论】:

  • 您是否使用SubmitNuevo 按钮进行导航
  • Logged 是否在 Route 中呈现,以便获得可用的路由道具?

标签: javascript reactjs react-router


【解决方案1】:

您需要使用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>
);

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 1970-01-01
    • 2019-01-19
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2023-01-11
    相关资源
    最近更新 更多