【问题标题】:Component is not getting rendered using router-link in React.js组件未在 React.js 中使用 router-link 呈现
【发布时间】:2019-06-04 08:51:15
【问题描述】:

来自 Navigation.js 的代码 sn-p

类导航扩展组件{ 使成为() { 返回(

    <Router>
 <nav className="navbar navbar-expand-lg navbar-light bg-light">
          <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span className="navbar-toggler-icon"></span>
    </button>

    <div className="collapse navbar-collapse" id="navbarSupportedContent">
      <ul className="navbar-nav mr-auto">

          <NavDropdown name="Test">
            <a className="dropdown-item" >

                <li><Link to={"/Invoice"} >Mexico Invoice</Link></li>

                   </a>
          </NavDropdown>

           <NavDropdown name="Analysis">
            <a className="dropdown-item" href="/Transaction">Audit Log</a>
        </NavDropdown>
      </ul>

   <Route exact path="/Invoice" component={Invoice}  />
             </div>
           </nav>
            </Router>
);

} }

用Router(导航)导出默认值

我正在从 App.js 渲染这个组件

class App extends Component {
  constructor(props) {
    super(props);

  }

  render() {
    return (
      <Router>
      <div >
        <HeaderAmex className="App" />
        <div>
   <Navigation/>
   </div>
   <Route exact path="/invoice" component={Invoice} /> 
         </div>
         </Router>
    );
  }
}

用Router(App)导出默认

下面是我的 Invoice.js

class Invoice extends Component {
  constructor(props) {
    super(props);
    this.state = { items: [], isLoaded: false, transId: "" ,flag:true,errorFlag:false,show:false,displayContent:"",invoice:"",invoiceXmlBody:"",invoiceTransId:"",invoiceResultFlag:false,invoicedisplayFlag:false};

  }



  handleChangeInvoice(e) {
    console.log("inside handleChangeInvoice");
    let invoiceXml = e.target.value;
    if (invoiceXml !== undefined) {
      this.setState({ invoiceXmlBody: e.target.value });
    }
  }

  handleSubmitInvoiceXml =e=>{
   console.log("*******************inside handleSubmitInvoiceXml***************");
   let url = "xxxxxx";
   fetch(url, {
    method: "POST",
    body: JSON.stringify(this.state.invoiceXmlBody),
    headers: {
      "Content-Type": "application/xml"
    },
    credentials: "xxxxx"
  }).then(res => res.json())
  .then(json => {
    this.setState({
      invoiceTransId:json,

    });
    if(json===undefined){
this.state.invoiceResultFlag=true;
    }
    else{

      this.state.invoicedisplayFlag=true;
      console.log("inside=========else===="+this.state.invoicedisplayFlag);
    }
    }
 ) }


  render() {
    const { match, location, history } = this.props
    console.log("---------------------------"+this.state.invoicedisplayFlag);
    return (

             <div className="App">
                <div>{location.pathname}</div>
        <br/>

          <label className="lable" style={{marginRight:19}}>
              InvoiceXml:
              <input
                type="text"
                name="invoiceXml" placeholder="Enter invoice xml" 
                onBlur={this.handleChangeInvoice.bind(this)}  style={{marginLeft:15}}
              />

            </label><br/><br/>


             <input type="button" onClick={this.handleSubmitInvoiceXml} name="Submit" value="Submit" className="submitButton"  style={{marginLeft:-60}}/>


            <br/>
            <br/><br/>



            <div  className={this.state.invoicedisplayFlag?"showDisplay":"hide"}>
            <h5>Transaction Id is :{this.state.invoiceTransId}</h5>



        </div>


      </div>
    );
  }
}

export default withRouter(Invoice)

下面是我的 index.js

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

 serviceWorker.unregister();

谁能帮我显示发票组件。我对 React 很陌生。

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

您收到此错误是因为 Navigation 组件在主路由器之外,并且组件路径应该是 path={''} 而不是 paths={''}

import { BrowserRouter as Router, Route } from 'react-router-dom';

 class App extends Component {
 constructor(props) {
  super(props);
 }

 render() {
   return (
   <Router>
    <div >
        <HeaderAmex className="App" />
        <div>
           <Navigation/>
        </div>

        <Route exact path="/" render={()=><h1>main<h1 />} /> 

        <Route path="/invoice" component={Invoice} /> 
    </div>
   </Router>    
   );
 }
 }

export default App;

为了访问组件中的位置道具,您必须使用 withRouter(Invoice) 扭曲 Invoice 组件

How to pass the React Router location prop to a component?

【讨论】:

  • 使用 withRouter(Invoice) 包装了 Invoice 组件,但仍然出现相同的错误:“无法读取未定义的属性 'location'” 以下是我所做的更改:render() { const { match , location, history } = this.props export default withRouter(Invoice)
  • 请编辑您的问题并添加发票组件代码我想查看完整代码
  • 嗯,看起来不错!您可以删除location.pathname 行并使用console.log(this.props) 检查渲染中的道具,看看位置是否仍然未定义
【解决方案2】:
import { BrowserRouter as Router, Route } from 'react-router-dom';

<Router>
   <div>
     <Route exact path="/" component={Home}/>
     <Route path="/news" component={NewsFeed}/>
   </div>
</Router>

这是react-router-dom的示例代码。您使用 Link 组件,该组件使用您之前应该定义的路由。 我认为您还缺少一些设置。您应该将您的应用包装在路由器中。

我希望这对你有帮助。不过好像你没看懂react-router-dom。阅读文档会对您有所帮助。

【讨论】:

  • 我已经更新了如下代码,但我仍然面临如下错误:"TypeError: Cannot read property 'location' of undefined"
  • 添加了以下路由器元素:
  • 您是否导入了一个名为Invoice 的组件?
  • 是发票组件已导入。
猜你喜欢
  • 2017-10-29
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 2018-05-20
相关资源
最近更新 更多