Reactjs 使用props重定向-反应路由器-无法读取未定义的属性“props”
我想重定向到一个名为SingleBook的特定组件,并发送一些道具bookId。我正在使用:反应路由器dom:^5.1.2 按照指南,我应该写下如下内容:Reactjs 使用props重定向-反应路由器-无法读取未定义的属性“props”,reactjs,react-router,Reactjs,React Router,我想重定向到一个名为SingleBook的特定组件,并发送一些道具bookId。我正在使用:反应路由器dom:^5.1.2 按照指南,我应该写下如下内容: return <Redirect to={{ pathname: "/book", state: { "bookId": "bookId" } }} /> 然而 它确实正确重定向到,但我得到错误: 无法读取未定义的属性“props” 我还尝试将我的路线定义为: <Rout
return <Redirect
to={{
pathname: "/book",
state: { "bookId": "bookId" }
}}
/>
然而
它确实正确重定向到,但我得到错误:
无法读取未定义的属性“props”
我还尝试将我的路线定义为:
<Route path="/book" component={SingleBook}/>
但我也犯了同样的错误
单书组件
由于您使用的是功能组件,您无权访问它,因此可以使用道具作为功能组件的参数。因此,该代码将起作用:
function SingleBook(props) { // Access props here without the {}
const bookId = props.location.state.bookId; // No `this`
console.log(bookId)
return(
<Grid>
single book {bookId}
</Grid>
)
}
export default SingleBook
你能给我们看一下SingleBook组件吗?我编辑了这个问题,包括component@FBSO,你能试试吗,const SingleBook={props}=>{…}?为什么状态:{bookId:bookId}和props.location.state.bookId而不是props:{bookId:bookId}和props.location.props.bookId?两者都有效,但其中一个更有意义吗?
<Route path="/book" component={SingleBook}/>
import React, {useEffect} from "react"
import Grid from '@material-ui/core/Grid';
function SingleBook({props}) { // I tried also without {props}
const bookId = this.props.location.state.bookId
console.log(bookId)
return(
<Grid>
single book {bookId}
</Grid>
)
}
export default SingleBook
function SingleBook(props) { // Access props here without the {}
const bookId = props.location.state.bookId; // No `this`
console.log(bookId)
return(
<Grid>
single book {bookId}
</Grid>
)
}
export default SingleBook
import React from "react"
import Grid from '@material-ui/core/Grid';
const SingleBook = () => {
let {location: {state : {bookId} = {}} = {}} = this.props;
let bookId = bookId;
console.log(bookId)
return(
<Grid>
single book {bookId}
</Grid>
)
}
export default SingleBook