我正在使用React Router挂钩进行导航useHistory
。
导航:history.push("/home", { update: true });
在家里:我正在尝试获取参数let {update} = useParams();
但是update
始终是未定义的。此代码有什么问题。有什么建议吗?
答案 0 :(得分:2)
history.push()
方法中的第二个参数实际上称为位置状态
history.push(path, [state])
如React-Router documentation所述,您可以通过访问location
道具来访问状态。根据您的情况,要获取update
的值,
this.props.location.update
答案 1 :(得分:2)
如果您使用的是React Hooks,请遵循此方法,因为 this.props 仅在React Class中可用。
组件一:
import React from 'react'
import { useHistory } from "react-router-dom";
const ComponentOne = () => {
const history = useHistory();
const handleSubmit = () => {
history.push('/component-two',{params:'Hello World'})
}
return (
<div>
<button onClick={() => {handleSubmit()}}>Fire</button>
</div>
)
}
第二部分:
import React from 'react'
import { useLocation } from "react-router-dom";
const ComponentTwo = () => {
const location = useLocation();
const myparam = location.state.params;
return (
<div>
<p>{myparam}</p>
</div>
)
}
答案 2 :(得分:0)
这是通过的方式
history.push("/home", { update: true });
,如果它是无状态组件,则这样访问。
props.location.update;
如果是基于类的组件。
this.props.location.update;
答案 3 :(得分:0)
如果您使用功能组件,还有一种更简单的方法来访问传递的状态:
首先在history.push中传入状态
history = useHistory();
history.push('/path-to-component-2', 'state')
接下来,您可以检索位置道具中的状态
const Component2 = ({ location }) => {
console.log(location.state);
return null;
};