使用 react-router 将回调函数作为 prop 传递给不同的路由
Pass callback function as prop to a different route using react-router
我正在尝试传递一个函数以用作不同路由中的回调。我知道可以这样做:
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.
A function
无法克隆或序列化。你想做的最好是作为 props
传递。在 history
上使用 state
对象非常奇怪。示例:
function FirstPage() {
// ...
return (
<>
<Link to='/secondpage'>go to second page</Link>
<Route
path='/secondpage'
render={() => <SecondPage myCallback={selectedPlaylist}}
/>
</>
);
}
如果你进一步扩展你想要完成的事情,它会更容易提供帮助。
我正在尝试传递一个函数以用作不同路由中的回调。我知道可以这样做:
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.
A function
无法克隆或序列化。你想做的最好是作为 props
传递。在 history
上使用 state
对象非常奇怪。示例:
function FirstPage() {
// ...
return (
<>
<Link to='/secondpage'>go to second page</Link>
<Route
path='/secondpage'
render={() => <SecondPage myCallback={selectedPlaylist}}
/>
</>
);
}
如果你进一步扩展你想要完成的事情,它会更容易提供帮助。