Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

reactjs - Can't figure out how to Link state with React Router

I have my "Link to" under a text field that updates my states but I get an error why I try the results.

The error I get is: TypeError: Cannot read property 'getProps' of undefined

This is my AdvancedSearch page:

<Link
    to={{
        pathname: "/Results",
        getProps: {
            searchGet: this.state.search,
            movieGet: this.state.movies,
            totalResultsGet: this.state.totalResults,
            currentPageGet: this.state.currentPage
        }
    }}>
        <Button variant='contained' > Show results </Button>
</Link>

And this is the Results page that I want the states to be transferred to:

const Results = (props) => {
        console.log("about",props.location.getProps)
        return (
            <div>
                Test
            </div>
        )
    }
question from:https://stackoverflow.com/questions/65894060/cant-figure-out-how-to-link-state-with-react-router

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is what the state prop is for. Docs here

Here is what you need. Your Link component should look like this:

 <Link
  to={{
     pathname: "/movie",
     state: {
       searchGet: "Val 1",
       movieGet: "Val 2",
       totalResultsGet: " Val 3",
       currentPageGet: "Val 4"
     }
  }}
 >
  Movie
 </Link>

And the way you would access that state in the Result component is...

const { searchGet, movieGet } = props.location.state;

This will only work though if you render your Result component as part of the Router like so:

<Switch>
...
...
  <Route path="/movie" component={Result} />
</Switch>

Here is a Sandbox for you to play around with.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...