使用react-router导航到具体的孩子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用react-router导航到具体的孩子相关的知识,希望对你有一定的参考价值。

我想通过按链接来导航到一个具体的子对象,例如“ / annotations / 1”,“ / annotations / 12”,但我不知道如何发送ID以从Child组件中的API获取。

我一直在尝试使用Link to =“ / annotationsView”,但是我无法获得单击的注释的具体ID。 我想单击注释的名称,然后转到/ annotationView / annotation ID,但是我不知道如何发送链接到AnnotationView组件以从API中获取数据。

return(
            <div>
                <h2>Anotaciones</h2>
                <div className="form-group">
                    <input type="date"/>
                </div>
                <Table>
                    annotations.map((ann) =>
                        <div>
                            <tr>
                                <Link to="/annotationView" id=ann.id>
                                    <th>ann.name</th>
                                </Link>
                            </tr>
                            <tr>
                                <td>ann.text</td>
                            </tr>
                        </div>
                    )
                </Table>
            </div>
        )

class AnnotationView extends Component 
    constructor(props) 
        super(props);

        this.state = 
            annotation: [],
            isLoading: false
        
    

    componentDidMount() 
        this.setState(isLoading: true);
        console.log(this.props.id);
        fetch("http://localhost:8080/annotations/" + this.props.params.id)
        .then(response => response.json())
        .then(data => this.setState(annotation: data, isLoading: false));
    

    render() 
        const  annotation, isLoading  = this.state;
        if(isLoading) 
            return <p>Loading...</p>;
        

        return(
            <div>
                <h2>Anotacion:  annotation.id </h2>
                <p>Título:  annotation.name </p>
                <p>Descripción:  annotation.text  </p>
        </div>
        )
    

您能解释一下如何在链接组件中发送ID或通过其他方式吗?

先感谢您。

答案

这是一个如何在url中传递参数的示例:

import React from 'react';
import  render  from 'react-dom';
import  BrowserRouter, Route, Switch  from 'react-router-dom'

const Item = ( match ) => 
  const  id  = match.params;
  return <h1>Item id</h1>


const App = () =>     
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/:id" component=Item />
      </Switch>
    </BrowserRouter>
  )


render(<App />, document.getElementById('root'));

例如,转到/2将显示Item 2

这里的例子。

以上是关于使用react-router导航到具体的孩子的主要内容,如果未能解决你的问题,请参考以下文章

react-router 出现奇怪的导航问题

使用 react-router 链接到其他组件

用于导航目录的react-router

使用带有 react-router 的锚点

在 react-router 4 中使用锚标签

导航离开然后返回页面时如何记住 React-Router URL 参数?