How to pass params with history.push/Link/Redirect in react-router v4?

前端 未结 10 913
你的背包
你的背包 2020-11-22 04:27

How can we pass parameter with this.props.history.push(\'/page\') in React-Router v4?

.then(response => {
       var r = this;
        if (re         


        
相关标签:
10条回答
  • 2020-11-22 04:54
    • For the earlier versions:

      history.push('/path', yourData);
      

      And get the data in the related component just like below:

      this.props.location.state // it is equal to yourData
      
    • For the newer versions the above way works well but there is a new way:

      history.push({
        pathname: '/path',
        customNameData: yourData,
      });
      

      And get the data in the related component just like below:

      this.props.location.customNameData // it is equal to yourData
      

    Hint: the state key name was used in the earlier versions and for newer versions, you can use your custom name to pass data and using state name is not essential.

    0 讨论(0)
  • 2020-11-22 04:55

    If you need to pass URL params

    theres a great post explanation by Tyler McGinnis on his site, Link to the post

    here are code examples:

    1. on the history.push component:

      this.props.history.push(`/home:${this.state.userID}`)

    2. on the router component you define the route:

      <Route path='/home:myKey' component={Home} />

    3. on the Home component:

    componentDidMount(){
        const { myKey } = this.props.match.params
        console.log(myKey )
    }
    
    0 讨论(0)
  • 2020-11-22 04:55

    To use React 16.8+(withHooks) you can use this way

    import React from 'react';
    import { useHistory } from 'react-router-dom';
    
    export default function SomeFunctionalComponent() {
    let history = useHistory(); // should be called inside react component
    
    const handleClickButton = () => {    
    "funcionAPICALL"
           .then(response => {
                 if (response.status >= 200 && response.status < 300) {
                     history.push('/template');
                  });
    }
    
    return ( <div> Some component stuff 
        <p>To make API POST request and redirect to "/template" click a button API CALL</p>
        <button onClick={handleClickButton}>API CALL<button>
    </div>)
    } 
    

    Source here to read more https://reacttraining.com/react-router/web/example/auth-workflow

    0 讨论(0)
  • 2020-11-22 05:04

    First of all, you need not do var r = this; as this in if statement refers to the context of the callback itself which since you are using arrow function refers to the React component context.

    According to the docs:

    history objects typically have the following properties and methods:

    • length - (number) The number of entries in the history stack
    • action - (string) The current action (PUSH, REPLACE, or POP)
    • location - (object) The current location. May have the following properties:

      • pathname - (string) The path of the URL
      • search - (string) The URL query string
      • hash - (string) The URL hash fragment
      • state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
    • push(path, [state]) - (function) Pushes a new entry onto the history stack
    • replace(path, [state]) - (function) Replaces the current entry on the history stack
    • go(n) - (function) Moves the pointer in the history stack by n entries
    • goBack() - (function) Equivalent to go(-1)
    • goForward() - (function) Equivalent to go(1)
    • block(prompt) - (function) Prevents navigation

    So while navigating you can pass props to the history object like

    this.props.history.push({
      pathname: '/template',
      search: '?query=abc',
      state: { detail: response.data }
    })
    

    or similarly for the Link component or the Redirect component

    <Link to={{
          pathname: '/template',
          search: '?query=abc',
          state: { detail: response.data }
        }}> My Link </Link>
    

    and then in the component which is rendered with /template route, you can access the props passed like

    this.props.location.state.detail
    

    Also keep in mind that, when using history or location objects from props you need to connect the component with withRouter.

    As per the Docs:

    withRouter

    You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as <Route> render props: { match, location, history }.

    0 讨论(0)
  • 2020-11-22 05:05

    It is not necessary to use withRouter. This works for me:

    In your parent page,

    <BrowserRouter>
       <Switch>
            <Route path="/routeA" render={(props)=> (
              <ComponentA {...props} propDummy={50} />
            )} />
    
            <Route path="/routeB" render={(props)=> (
              <ComponentB {...props} propWhatever={100} />
              )} /> 
          </Switch>
    </BrowserRouter>
    

    Then in ComponentA or ComponentB you can access

    this.props.history

    object, including the this.props.history.push method.

    0 讨论(0)
  • 2020-11-22 05:06

    you can use,

    this.props.history.push("/template", { ...response }) or this.props.history.push("/template", { response: response })

    then you can access the parsed data from /template component by following code,

    const state = this.props.location.state

    Read more about React Session History Management

    0 讨论(0)
提交回复
热议问题