ReactJS: React-Router pass value to another page

柔情痞子 提交于 2021-02-11 18:16:22

问题


I have need to pass a value from a page to another using react-router.

I have tried in this way:

<li>
    <A 
      className="btn btn-link btn-sm"
      href={{ pathname: Routes.detail_page, search: `?_id=${C.Code}`, state: this.props.current  }}>
      { 'Open' }
    </A>
</li>

I would pass this.props.current to Detail Page.

In the other page if I tried in the componentDidMount() to print this.props.current it result undefined (of course in the first page this value is parametrized).

constructor(props){
    super(props);
    this.state = {
    };
  }
componentDidMount(){
    let C = this.props.current
    console.log("C is: ", C) // this is undefined
    this.updateIsDeletableState()
  }

How can I do?


回答1:


You have to make sure that you have defined URL parameter in the Route

// file-where-you-define-routes.js
...
<Switch>
  <Route path={`your-path/:id`} component={YourComponent} />
</Switch>
...

Then use hook useParams to get the parameter

function YourComponent() {
  const { id } = useParams();
  let C = id;
  console.log("C is: ", C) // this should be defined now
  ...
}

OR if you use class component this.props.match.params.id

class YourComponent extends Component {
  ...
  componentDidMount(){
    let C = this.props.match.params.id; // match
    console.log("C is: ", C) // this should be defined now
    this.updateIsDeletableState()
  }
}


来源:https://stackoverflow.com/questions/62571061/reactjs-react-router-pass-value-to-another-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!