withRouter params解析不变违规时出错:您不应该在<router>之外使用<route>或withRouter()

时间:2018-03-30 15:59:24

标签: reactjs react-router

所以我一直试图使用withRouter传递一个参数,但我发现不变违规的错误:你不应该在路由器外使用Route或withRouter()

你们中的任何人都知道如何修复它吗?或传递参数使用withRouter旁边的任何东西?

这是我的代码

import React, { Component } from 'react';
import dummy_database from '../../file_source/dummy_database.json';
import {withRouter} from 'react-router';
import './css/description.css';

class Description extends Component {
    render() {
        var id = parseInt(this.props.match.params.id, 10);
        var contentKeys = Object.keys(dummy_database.products);
        var products = contentKeys.map((t) => 
            <p key={t}>{dummy_database.products[t]}</p>
        );

        var description='';

        for(var i = 0; i < products.length; i++){
            if(dummy_database.products[i].id === id){
                description = dummy_database.products[i].description;
            }
        }
        return (
            <div className="description">
                <div className="descriptionTitle">
                    <h3>Description</h3>
                </div>
                <div className="descriptionText">
                    {description}
                </div>
            </div>
        );
    }
}

export default withRouter(Description);

这是我使用的按钮代码

import React, { Component } from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import Details from '../../pages/details/details';


class ViewButton extends Component {
    refreshPage() {
        window.location.reload();
    }

    render() {

        var link = 'details/' + this.props.id;
        return (
            <div>
                <BrowserRouter>
                    <button>
                        <Link to={link} onClick={this.refreshPage}>View Detail</Link>
                    </button>
                    <Route path={link} component={Details} />
                </BrowserRouter>
            </div>
        );
    }
}
export default ViewButton;

提前致谢

1 个答案:

答案 0 :(得分:0)

结帐documentation for BrowserRouter:

  

children:node要呈现的单个子元素。

通过将一个节点作为BrowserRouter的子节点

来修复它
import React, { Component } from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import Details from '../../pages/details/details';


class ViewButton extends Component {
    refreshPage() {
        window.location.reload();
    }

    render() {

        var link = 'details/' + this.props.id;
        return (
            <div>
                <BrowserRouter>
                  <div>
                    <button>
                        <Link to={link} onClick={this.refreshPage}>View Detail</Link>
                    </button>
                    <Route path={link} component={Details} />
                  </div>
                </BrowserRouter>
            </div>
        );
    }
}
export default ViewButton;