ReactJS 中的参数路由不显示 UI 组件

Posted

技术标签:

【中文标题】ReactJS 中的参数路由不显示 UI 组件【英文标题】:Parameter Route in ReactJS not show UI Component 【发布时间】:2020-03-06 19:06:36 【问题描述】:

我使用 Laravel 作为后端,使用 ReactJS 作为前端。在 ReactJS 中,创建路由。 在 Laravel 中,创建 Api。当我将参数从 ReactJS 解析到 Laravel 时,第一次没问题。重新加载这些页面后,仅显示 Json

我尝试了像“/:id”这样的参数路由并且工作。但是对于多个对象它没有解决。它只适用于一个对象。

App.js

import React,  Component  from 'react'
import ReactDOM from 'react-dom'
import  BrowserRouter, Route, Switch, browserHistory,IndexRoute  from 'react-router-dom'
import NewApp from './NewApp'
import AppList from './AppList'
import NAVBAR from './NAVBAR'
import Container from './Container'
import MainNavigation from './MainNavigation'
import AppSettingList from './AppSettingList'
import UpdateApp from './UpdateApp'
import withRouter from 'react-router';

class App extends Component 
  render () 
    console.log(window.location.pathname);
    return (
      <BrowserRouter>
        <div>
          /* <Header /> */
          <NAVBAR />
          <MainNavigation />
          <Switch>

            <Route exact path='/' component=withRouter(Container) />
            <Route exact path='/dashboard/' component=withRouter(Container) />
            <Route exact path='/app/' component=withRouter(AppList) />

            <Route exact path='/app/:id' component=withRouter(UpdateApp) />

            <Route exact path='/appsetting/' component=withRouter(AppSettingList) />
            <Route exact path='/app/create' component=withRouter(NewApp) />

          </Switch>
        </div>
      </BrowserRouter>
    )
  


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

UpdateApp.js

 import axios from 'axios'
import React,  Component  from 'react'
import NiftySuccessModal from './alerts/NiftySuccessModal'

class UpdateApp extends Component 
  constructor (props) 
    super(props)

    this.state = 
      name: '',
      description: '',
      errors: [],
      apps : [],
      id : 0,
      loading : false,
      successModal : false
    ;
    // binding
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.hasErrorFor = this.hasErrorFor.bind(this);
    this.renderErrorFor = this.renderErrorFor.bind(this);
    this.showSuccessModal = this.showSuccessModal.bind(this);
    this.getApp = this.getApp.bind(this);
    this.gotoApp = this.gotoApp.bind(this);
  

  getApp(appId)


    axios.get(`/app/$appId`).then(response =>  // return value
        this.setState(
            apps: response.data.apps,
            name : response.data.apps.name,
            id : response.data.apps.id
        );
        console.log(response.data.apps);

    );

  
  componentDidMount () 
    const appId = this.props.match.params.id;
    this.getApp(appId);
  

  gotoApp()  
    this.props.history.push('/app');
  

  handleChange(e)
    this.setState(
        name: e.target.value
    );


  showSuccessModal(e)
    this.setState(
      successModal : true
    );


    setTimeout(() => 
      this.setState(
        successModal: false
      )
      , 10000);

  


  hasErrorFor (field) 
    return !!this.state.errors[field]
  

  renderErrorFor (field) 
    if (this.hasErrorFor(field)) 
      return (
        <span className='invalid-feedback'>
          <strong>this.state.errors[field][0]</strong>
        </span>
      )
    
  



  handleSubmit(e)
    e.preventDefault();

    const params = 
        id : this.state.id,
        name: this.state.name      
    

        console.log('Update');
        axios
          .post('/app/update', params)
          .then(response => 
            console.log('Success');
          )
          .catch(error => 
            console.log('Error');
            this.setState(
              errors: error.response.data.errors
            );

          )


  render () 
    return (

        <div id="content-container">
                <div id="page-head">

                <div className="pad-all text-center">
                <h3>Welcome back to the Dashboard.</h3>
                <p>Scroll down to see quick links and overviews of your Server, To do list, Order status or get some Help using Nifty.</p>
                </div>
                                </div>
            <div id="page-content">

      <div className="row">
        <div className="col-md-1"></div>
      <div className="col-lg-9">

      <NiftySuccessModal show=this.state.successModal > Successfully Updated! </NiftySuccessModal>

          <div className="panel">
              <div className="panel-heading">
                  <h3 className="panel-title">App </h3>
              </div>


              <form className="panel-body form-horizontal form-padding" onSubmit=this.handleSubmit>

                  <div className="form-group">
                      <label className="col-md-3 control-label" >App Name</label>
                      <div className="col-md-9">
                          <input type="text"
                          name='name'
                          id='name'
                          onChange=this.handleChange
                          value=this.state.name
                          className="form-control"
                          maxLength="255"
                          placeholder="App Name..."
                          required  className="form-control" placeholder="Text" />
                          <small className="help-block">This is a help text</small>
                      </div>
                  </div>
                  <div className="form-group demo-nifty-btn col-md-3">
                  <input type="submit" onClick=this.showSuccessModal value="Update" className="form-control btn btn-primary" />
                  </div>
              </form>
            </div>
            </div>
            </div>
          </div>/* End <!--Page content--> */

          </div> // End <!--CONTENT CONTAINER-->
    )
  




export default UpdateApp

![重载前]: (https://i.imgur.com/rWqFo9Y.png) ![重载后]: (https://i.imgur.com/maR3x1S.png)

【问题讨论】:

【参考方案1】:

现在解决了!在 React Router 中使用不同的路由名称和查询字符串。 Page Reload 也可以。谢谢。

that is not working
<Route path='/app' component=withRouter(AppList) />
<Route path='/app/:id' component=withRouter(UpdateApp) />

working with Query String

<Route path='/updateapp' component=withRouter(UpdateApp) />

【讨论】:

以上是关于ReactJS 中的参数路由不显示 UI 组件的主要内容,如果未能解决你的问题,请参考以下文章

ReactJS:从 rails 传递参数以将路由器反应到组件

如何从 ReactJS 组件调用 Laravel Api 路由?

Reactjs - 路由不适用于导入的组件

如何结合 ReactJs Router Link 和 material-ui 组件(如按钮)?

创建组件后,reactJS 材料 ui 中的平滑崩溃损坏

Reactjs - 通过在自动完成组件(材料 UI)中的每个输入更改上点击 API 来更新选项