在React路由器的Link标签中使用状态传递数据

时间:2018-09-19 11:01:15

标签: reactjs react-router

我不知道我哪里错了。我想将该参数作为状态传递给Link标签,并在另一个组件中获取它。

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

export default class CategoryList extends React.Component{


    render(){
        return(
            <tr>
                <td>
                    <Link to={{pathname:"/Topics/" + this.props.row.Occupation+"/"+this.props.row.objectId +'/id'+'/'+this.props.userName, state:{description:this.props.row.Description}}}>
                        {this.props.row.Occupation}
                    </Link>
                </td>
                <td>{this.props.row.Description}</td>
            </tr>
        )
    }
} 

index.js

<Route path="/Topics/:Occupation/:objectId/:id/:userName" component={Main} />

我想在这里传递它并访问Link标记中给出的状态。因此,您的帮助会很棒。

4 个答案:

答案 0 :(得分:2)

您无需将任何其他值传递给路由。您可以通过向链接对象提供额外的对象来实现所需的目标。

-

 <Link to={{pathname:"/Topics/", customObject: customValue}}>

,然后您可以从this.props.location.customObject

访问它

答案 1 :(得分:1)

在将数据传递给链接中的状态对象之后,您可以在路由组件(如果是主组件)中访问此数据,如下所示:

import re

class text_processing:

    def __init__(self,file_name):
        print ("File opened")
        self.file_name = file_name
        self.search_pat = 'DEBUG Facebook'


    def search(self):
        print ("in sreach function")
        for line in self.file_name:
            print (line)
            if self.search_pat in line:
                print (self.line)
                for i in self.search_pat:
                    print re.findall(r"\d\d\d\d-\d\d-\d\d", self.search_pat)
                    break

def main():
    filename = 'sample1.txt'
    file_open = open(filename, "r")
    x = text_processing(file_open)
    x.search()

答案 2 :(得分:1)

根据docs,您可以执行以下操作

<Link to={{ pathname: '/hello', query: { name: 'ryan' } }}> Hello </Link>

在新路径中,您可以使用道具获得该名称。

答案 3 :(得分:0)

我知道我提供解决方案的时间太晚了,您可能已经找到了解决方案,但是我的解决方案也可以用于面临相同问题的其他人。我已经做了类似的事情

public loadPage(data) {
    browserHistory.push({
        pathname: '/am/activate',
        state: data
    });
}

在其他组件上,您可以访问该值

this.props.location.state