P03: dynamic value transfer of react router route

elaborate

In the previous section, we solved the problem of link jump. Now imagine such a scenario. In a list page of many articles, and then click any link, you can accurately open the detailed article content. This needs to pass the article ID, then accurately retrieve the article content in the background, and finally present it.

In this process, the ID value passed to the detailed page is different every time, so the route needs to have the ability of dynamic value transmission.

Allow dynamic value transfer on Route

This setting starts with: followed by the key name you passed.
Let's take a simple example:

ReactRouterDemo\demo01\src\AppRouter.js

<Route path="/list/:id" component={List} />

After reading the code, you will find it very simple to add: id to the path.
This sets the rules for allowing value transfer.

Link upload value

After setting the rule, you can set the value on the Link. Now you can set the id value to be passed. At this time, you don't need to add id, just write the value directly.

<li><Link to="/list/123">list</Link> </li>

Now you can transfer values.

Receive and display the passed values on the List component

When the component receives the passed value, it can be carried out in the declaration cycle componentDidMount. The passed value is in this props. Match.

We can print it first. The code is as follows:

ReactRouterDemo\demo01\src\Pages\List.js

import React, { Component } from 'react';

class List extends Component {
    constructor(props) {
        super(props);
        this.state = {  }
    }
    render() { 
        return (  <h2>List Page</h2> );
    }
    //-Key code ----------- start
    componentDidMount(){
        console.log(this.props.match)
    }
    //-Key code ------------ end
}

export default List;

Then you can see the printed object in the browser console. The object includes three parts:

1. patch: Custom routing rules. You can clearly see that id parameters can be passed.
2. url: the real access path, where you can clearly see the parameters passed.
3. params: passed parameters, key and value values.

After understanding the object properties in match, you can easily obtain the passed ID value. The code is as follows:

ReactRouterDemo\demo01\src\Pages\List.js

import React, { Component } from 'react';

class List extends Component {
    constructor(props) {
        super(props);
        this.state = {  }
    }
    
	//-Key code ----------- start
    render() { 
        return (  
            <h2> List Page-> {this.state.id}</h2>
        );
    }

    componentDidMount(){
        // console.log(this.props.match.params.id)
        let tempId=this.props.match.params.id;
        this.setState({id:tempId });
     }
    //-Key code ------------ end
}

export default List;

In this way, the dynamic value transmission is realized. It should be noted that if you do not transmit anything, there is no way to match the route successfully.

Of course, the value of dynamic transmission mentioned above is written dead and lacks flexibility, but it has told you a lot of theories of dynamic transmission of value, which can be regarded as a preliminary understanding of the dynamic transmission of value by React Router.

Simulate a list array

Next, do a small exercise according to the above basic theoretical knowledge, vividly simulate a dynamic data list, and transfer the values in the list to the details page.

Now you can simulate a list array in the Index component, which is equivalent to the content we dynamically get from the background, and then the array includes the cid and title of the article.

Set directly during state initialization. The code is as follows:

ReactRouterDemo\demo01\src\Pages\Index.js

constructor(props) {
    super(props);
    this.state = { 
        list:[
            {uid:123,title:'willem-1'},
            {uid:456,title:'willem-2'},
            {uid:789,title:'willem-3'},
        ]
    }
}

After you have the list array, modify the UI for effective traversal. The Render code is as follows:

render() { 
    return ( 
        <ul>
            {
                this.state.list.map((item,index)=>{
                    return (
                        <li key={index}> {item.title} </li>
                    )
                })
            }
        </ul>
    )
}

The list can be displayed in the Index component. Next, you can configure < Link >. Before configuration, you need to introduce the Link component.

import { Link } from "react-router-dom";

After the introduction, you can directly use it to jump, but you should pay attention to the form of {}, that is, parse the content in to into JS, so as to pass the value smoothly.

render() { 
    return ( 
        <ul>
            {
                this.state.list.map((item,index)=>{
                    return (
                        <li key={index}>
                            <Link to={'/list/'+item.uid}> {item.title}</Link> 
                        </li>
                    )
                })
            }
        </ul>
    )
}

So far, it is very similar to the list in our project to transfer values to the details page.

Example

ReactRouterDemo\demo01\src\index.js

import React from 'react';
import ReactDOM from 'react-dom'
import AppRouter from './AppRouter'

ReactDOM.render(<AppRouter/>,document.getElementById('root'))

ReactRouterDemo\demo01\src\AppRouter.js

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Index from './Pages/Index'
import List from './Pages/List'

function AppRouter() {
  return (
    <Router>
        <ul>
            <li> <Link to="/">home page</Link> </li>
            <li><Link to="/list/123">list</Link> </li>
        </ul>
        <Route path="/" exact component={Index} />
        <Route path="/list/:id" component={List} />
    </Router>
  );
}

export default AppRouter;

ReactRouterDemo\demo01\src\Pages\Index.js

import React, { Component } from 'react';
import { Link } from "react-router-dom";

class Index extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            list:[
                {uid:123,title:'willem-1'},
                {uid:456,title:'willem-2'},
                {uid:789,title:'willem-3'},
            ]
        }
    }
    render() { 
        return ( 
            <ul>
                {
                    this.state.list.map((item,index)=>{
                        return (
                            <li key={index}>
                                <Link to={'/list/'+item.uid}> {item.title}</Link> 
                            </li>
                        )
                    })
                }
            </ul>
        )
    }
}

export default Index;

ReactRouterDemo\demo01\src\Pages\List.js

import React, { Component } from 'react';

class List extends Component {
    constructor(props) {
        super(props);
        this.state = {  }
    }

    render() { 
        return (  
            <h2> List Page-> {this.state.id}</h2>
        );
    }

    //-Key code ----------- start
    componentDidMount(){
        // console.log(this.props.match.params.id)
        let tempId=this.props.match.params.id;
        this.setState({id:tempId });
     }
    //-Key code ------------ end
}

export default List;

Keywords: Javascript Front-end React

Added by kiosklim on Thu, 16 Dec 2021 07:57:29 +0200