reactjs - 使用 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。
有没有办法做到这一点?
谢谢
解决方案
使用useHistory。执行 history.push 并提供一个对象,pathname
您data
需要将其传递给要重定向的组件。
...
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);
推荐阅读
- javascript - 尝试使用 Vue.js 访问 Stack Oveflow Api 出现错误
- android - 如何修复无法读取序列化文件指纹。在数据流中发现无法识别的值
- python - Django 无法登录用户
- python - 您可以自行签署 pyinstaller 程序,以便在将其提供给其他人时不会显示为病毒吗?
- java - 下载文件android的异常
- docker - Traefik 2 - 尝试将我的第一个容器配置为使用 traefik
- c# - 重新加载时重置分数
- javascript - JavaScript p5.js 游戏中的敌人检测和炮塔动画/控制
- android - 使用浮动或分数样式资源的自定义视图崩溃
- c++ - 与串行版本相比,使用 openMP 的插入排序的并行化给出了非常尖锐的结果