gpt4 book ai didi

reactjs - 使用 react-router 将回调函数作为 prop 传递给不同的路由

转载 作者:行者123 更新时间:2023-12-04 08:45:10 26 4
gpt4 key购买 nike

我正在尝试传递一个函数以用作不同路由中的回调。我知道可以这样做:

import { useHistory } from "react-router-dom";

const FirstPage = props => {
let history = useHistory();

const someEventHandler = event => {
history.push({
pathname: '/secondpage',
state: { detail: 'some_value' }
});
};

};
但是当我尝试传递这样的回调函数时出现此错误:
我的回调代码:
    const someEventHandler = event => {
history.push({
pathname: '/secondpage',
state: { my_callback: selectedPlaylist }
});
};
错误:
DataCloneError: Failed to execute 'pushState' on 'History': selectedPlaylist => {
....
}
这是因为它是对函数的引用而不一定是状态而无法完成的事情吗?有解决方法吗?我找不到任何与此类似的资源。提前致谢!

最佳答案

MDN说:

The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.


一个 function不能被克隆或序列化。你要做的最好被传为 props .使用 state反对 history很奇怪。例子:
function FirstPage() {
// ...
return (
<>
<Link to='/secondpage'>go to second page</Link>
<Route
path='/secondpage'
render={() => <SecondPage myCallback={selectedPlaylist}}
/>
</>
);
}

如果您在想要完成的事情上扩展更多,那么帮助就会变得更容易。

关于reactjs - 使用 react-router 将回调函数作为 prop 传递给不同的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64362660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com