首页 > 解决方案 > 使用 React 中的 Props 以编程方式链接到组件(Hooks)

问题描述

我试图在点击后重定向到一个组件。我需要给它发送一些状态或道具。

我可以使用 Link 组件来做到这一点;IE

<Link to={pathname: '/messages', state: { id: post.id}} ... 

这重定向到组件,我可以从新组件的位置获取状态。

但是,我需要先对点击执行一些操作,所以我不能(或不知道如何)以编程方式使用 state/props 重定向。

我可以用

.....

history = useHistory()
function func() 
{
     //send ajax request
     history.push()
}

....

<button onClick={func}....>Save Todo</button>

这将带我到组件,但我也需要传递 id。

有没有办法做到这一点?

谢谢

标签: reactjsreact-routerreact-hooks

解决方案


使用useHistory。执行 history.push 并提供一个对象,pathnamedata需要将其传递给要重定向的组件。

...
history = useHistory()
const handleClick = () => {    
    apiService('myEndpoint')
        .then(response => {
           history.push({
             pathname: '/myPath',
             state: { id: response.data.id } // <----- send your id here
        });
    }
}

在接收组件中:

    ...
    useEffect(() => {
       console.log(props.location.customNameData);
    }, []);

注意:您也可以使用useLocation

import { useLocation } from "react-router-dom";
console.log(location.state.id);

推荐阅读