Javascript 在React js中重定向时将参数传递到新页面
当从当前页面进行定向时,我正在努力将参数传递到新页面 这是我的当前页面,名为Javascript 在React js中重定向时将参数传递到新页面,javascript,reactjs,parameters,properties,Javascript,Reactjs,Parameters,Properties,当从当前页面进行定向时,我正在努力将参数传递到新页面 这是我的当前页面,名为SingleBox function SingleBox(props){ let history = useHistory(); function moveToSinglePost() { history.push({ pathname: "/single-post", state: props })
SingleBox
function SingleBox(props){
let history = useHistory();
function moveToSinglePost() {
history.push({
pathname: "/single-post",
state: props
})
}
return(
// <></>
<Grid item md = {4} css = {GridCell}>
<div onClick = {moveToSinglePost}>
<Grid style = {singleBox}>
<img style = {singleImage} src = {props.BoxProps.val.image} />
<p style = {userDisplay}> {props.BoxProps.val.user}</p>
</Grid>
</div>
</Grid>
)
}
我在SinglePostView
中打印的道具与我想要的不同(包含val、key等):
如果你像那样传递道具,它们可以在react router的location对象中检索(在SinglePostView中)
您可以访问传递的道具,如
this.props.location.state
请像这样试试
function SingleBox(props){
let history = useHistory();
function moveToSinglePost() {
history.push({
pathname: "/single-post",
state: props
})
}
return(
// <></>
<Grid item md = {4} css = {GridCell}>
<div onClick = {moveToSinglePost}>
<Grid style = {singleBox}>
<img style = {singleImage} src = {props.BoxProps.val.image} />
<p style = {userDisplay}> {props.BoxProps.val.user}</p>
</Grid>
</div>
</Grid>
)
}
功能单盒(道具){
让历史=使用历史();
函数moveToSinglePost(){
历史推送({
路径名:“/single post”,
国家:道具
})
}
返回(
//
{props.BoxProps.val.user}
)
}
在SinglePostView中
const location = useLocation()
const { props } = location.state
function SinglePostView(props){
console.log("singlePostView", this.props.location.state);
return (
<>
<AppNavBar/>
<Grid>
<Grid item md = {6} style = {post}>
<Grid container style = {displayImage} >
<Grid item style = {singleBox}>
{/* <img src = "this.props.location.state.link"/> */}
</Grid>
</Grid>
</Grid>
</Grid>
</>
)
}
函数SinglePostView(道具){
log(“singlePostView”,this.props.location.state);
返回(
{/* */}
)
}
请使用Singlepostview中的this.props.location.state
引用singleBox中的参数
function SingleBox(props){
let history = useHistory();
function moveToSinglePost() {
history.push({
pathname: "/single-post",
state: props
})
}
return(
// <></>
<Grid item md = {4} css = {GridCell}>
<div onClick = {moveToSinglePost}>
<Grid style = {singleBox}>
<img style = {singleImage} src = {props.BoxProps.val.image} />
<p style = {userDisplay}> {props.BoxProps.val.user}</p>
</Grid>
</div>
</Grid>
)
}
function SinglePostView(props){
console.log("singlePostView", this.props.location.state);
return (
<>
<AppNavBar/>
<Grid>
<Grid item md = {6} style = {post}>
<Grid container style = {displayImage} >
<Grid item style = {singleBox}>
{/* <img src = "this.props.location.state.link"/> */}
</Grid>
</Grid>
</Grid>
</Grid>
</>
)
}