React 6 navigation and clicks not working as expected

问题: Sorry to ask so many questions, but this only my second and 1/2 week working with React. When I click on the following links, I can see the URL/URI change in the browser,...

问题:

Sorry to ask so many questions, but this only my second and 1/2 week working with React.

When I click on the following links, I can see the URL/URI change in the browser, but it does not seem to load the component(s). What am I missing?

import React from "react";
import { Link } from "react-router-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";
import NewComponent from "./new.component";
import ListComponent from "./list.component";

class NavComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: [] };
  }

  render() {
    return (
      <div className="row">
        <div className="col-sm-8 col-sm-offset-2">
          <nav className="navbar navbar-default">
            <div className="container-fluid">
              <div className="navbar-header">
                <a className="navbar-brand">Simple CRUD</a>
              </div>
              <div id="navbar" className="navbar-collapse">
                <ul className="nav navbar-nav">
                  <li>
                    <a href="#/">Coin Management</a>
                  </li>
                  <li>
                    <a href="#/add">Add Coin</a>
                  </li>
                </ul>
              </div>
            </div>
          </nav>
          <Router>
            <Route path={"ListComponent"} component={ListComponent} />
          </Router>
          <Router>
            <Route path={"NewComponent"} component={NewComponent} />
          </Router>
        </div>
      </div>
    );
  }
}

export default NavComponent;

I have tried to use Link to={"/"} and Link to={"/add"}, but the error will be - Link should be used within the Router. I know that I am missing something simple.

I have also tried creating some onClick={"window.location.href=/add"} but I received the error - Expected onClick listener to be a function, instead got a value of string type

The same error message when I use onClick='{window.location.href="/add"}' - it does look like it is trying to do it.

Do I have to build a router group, like I did in Laravel? if so, then can you point me to some examples?

The following is the NewComponent that I want the app to navigate to or load in place of the ListComponent:

import React from "react";
import Axios from "axios";
import toastr from "toastr";
import $ from "jquery";
import bootstrap from "bootstrap";
import ListComponent from "./list.component";

class NewComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: null,
      price: null
    };
  }

  submitForm(event) {
    event.preventDefault();
    var data = $(event.target).serialize();
    toastr.clear();
    var isError = false;
    if (this.state.name === "") {
      toastr.error("Coin name must be filled!");
      isError = true;
    }
    if (this.state.price === 0 || this.state.price === "") {
      toastr.error("Coin price must be filled!");
      isError = true;
    }
    if (!isError) {
      toastr.info("Inserting new coin data...");
      Axios.post(
        "http://local.kronus:8001/v2018/ng6crud/api/put-coins/" +
          this.state.id +
          "/" +
          this.state.name +
          "/" +
          this.state.price,
        {
          id: this.state.id,
          name: this.state.name,
          price: this.state.price
        }
      )
        .then(function(response) {
          toastr.clear();
          window.location.href = "#/";
        })
        .catch(function(error) {
          toastr.clear();
          toastr.error(error);
        });
    }
  }

  onCoinNameChange(e) {
    this.setState({
      id: this.state.id,
      name: e.target.value.trim(),
      price: this.state.price
    });
  }

  onCoinPriceChange(e) {
    this.setState({
      id: this.state.id,
      name: this.state.name,
      price: e.target.value
    });
  }

  render() {
    return (
      <div>
        <form className="form-horizontal" onSubmit={this.submitForm.bind(this)}>
          <div className="form-group">
            <label className="control-label col-sm-2" htmlFor="coinEmail">
              Name :{" "}
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                name="coinName"
                onChange={this.onCoinNameChange.bind(this)}
                id="coinName"
                className="form-control"
                placeholder="Coin Name"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="control-label col-sm-2" htmlFor="coinPrice">
              Price :{" "}
            </label>
            <div className="col-sm-10">
              <input
                type="number"
                name="coinPrice"
                onChange={this.onCoinPriceChange.bind(this)}
                id="coinPrice"
                className="form-control"
                placeholder="Coin Price"
              />
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-offset-2 col-sm-10">
              <button type="submit" className="btn btn-default">
                Save
              </button>
            </div>
          </div>
        </form>
      </div>
    );
  }
}

export default NewComponent;

BTW, zero errors and a few warnings about bootstrap as being defined but never used

Once again, thanks in advance


回答1:

As @tholle said in the comments, you should only have a single Router component wrapping the entirety of your app. Normally this is done at the top most component so something like

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter } from 'react-router-dom';

import App from './components/App';
import './index.css';

ReactDOM.render(
  // here is where we are wrapping our app, <App /> in <BrowserRouter />
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root'));
registerServiceWorker();

This is normally how a Create-React-App app is set up so whatever you are using YMMV. Just remember to wrap your top level component, usually <App /> in the <BrowserRouter /> or in your code <Router /> component.

Now on to your <Route /> components, curly braces are only necessary when we need to pass JS into our components attributes. In your example, <Route path={"ListComponent"} component={ListComponent} /> the path attribute needs to be a URL, in relation to the home page, that will be responsible for rendering that component. So something more like <Route path='./list' component={ ListComponent } /> is just fine. If you needed to pass a variable into path then you would use the curly braces like so ...path={ var + '/list' }....

Lastly, to get your <NewComponent /> to load you need to import { Link } from react-router-dom and instead of using those anchor tags, use <Link to='/add'>Links to the NewComponent component</Link> and just make sure your Route component that renders the NewComponent's path attribute matches.

Helpful links

React Router 4 - Quickstart


回答2:

  • Change anchor tags to Link

  • Change route path to url

https://reacttraining.com/react-router/web/example/basic

Follow react router example for better understanding

  • 发表于 2018-07-12 01:02
  • 阅读 ( 365 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除