当我链接到React.js中的不同页面时,如何传入数字?

时间:2017-10-11 10:18:08

标签: javascript reactjs

render(

    <Router>
        <Switch>
            <Route exact path="/" component = { Home } />
            <Route exact path="/gallery" component = { Gallery } />
            <Route exact path="/details" component = { Details } />
        </Switch>
    </Router>,

    // Define your router and replace <Home /> with it!
    document.getElementById('app')
);

以下是我的网络应用的路由

        return data.map((eachData, index) => {
            return (  <Link to={{ pathname: '/details/' + this.state.selectedKey }}><PokemonInfo poke={ eachData } key={ index } /></Link> );
        });
    };

当我移动到另一个链接时,这是我尝试链接到/ details页面的代码部分。我想传入一个数字(不是状态。不像我的示例代码)。

简单地说,我想传入,让我们说2,进入链接,然后直接转到/ details / 2,然后检索“&#39; 2&#39;在details.jsx组件中。

我该怎么做?

编辑:详情

class Details扩展了React.Component {

constructor() {
    super();


    this.state = {


        pokemon: []

    };


};

componentWillMount() {
// Called first time the comp is loaded right before the comp is added to the page
    console.log('Component WILL MOUNT!')
    console.log("passed" , this.props.match.params.id)
    var url = "https://pokeapi.co/api/v2/pokemon/" + this.props.match.params.id; 

    axios.get(url)

    .then((response) => {
        // setState re-renders component
        this.setState({
            pokemon: response.data
        })

        console.log(this.state.pokemon)

    })

        .catch((error) => {
            console.log(error);
    })
}

render() {

    return (
            <Card className = "PokemonView">
                <Card.Content>
                    <Card.Header className = "PokemonView_header">
                        { this.state.pokemon.name }
                    </Card.Header>
                    <Card.Meta>
                        Pokedex #{ this.state.pokemon.id }
                    </Card.Meta>
                    <Card.Meta>
                        Height { this.state.pokemon.height }
                    </Card.Meta>
                    <Card.Meta>
                        Weight { this.state.pokemon.weight }
                    </Card.Meta>

                </Card.Content>
            </Card>
    );
}

}

导出默认详细信息

3 个答案:

答案 0 :(得分:1)

如果我没记错的话,你可以设置如下路线:

<Route path="/details/:id" component = { Details } />

然后在Details组件中,您可以使用this.props.match.params.id

答案 1 :(得分:1)

您必须添加路由:grep(),并且可以在详细信息组件中检索带有<Route path="/details/:myParam" component={Details} />的路由参数。

答案 2 :(得分:1)

尝试使用

<Route path="/details/:id" component={(props) => (<Details {...props}/>) } />