反应路由-通过id

时间:2020-03-07 20:52:24

标签: javascript reactjs

我能够下载提交给表单的数据。单击id之后,我想使用路由转到新页面并写入下载记录的数据。单击链接后,我转到正确的路径,但是视图保持不变。进入新页面时,应用程序状态会被删除吗?

List.js

import React, { Component } from "react";
import {
  Switch,
  Route,
  BrowserRouter,
  Router,
  NavLink
} from "react-router-dom";
import Single from "./Single";
class List extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      login: "",
      pass: ""
    };

    this.add = this.add.bind(this);
    this.show = this.show.bind(this);
    this.del = this.del.bind(this);
  }

  add(e) {
    e.preventDefault();
    this.setState({
      [e.target.name]: e.target.value
    });
  }

  show(e) {
    e.preventDefault();

    if (!this.state.login.length || !this.state.pass.length) {
      return;
    } else {
      const newUser = {
        login: this.state.login,
        pass: this.state.pass
      };

      this.setState(state => ({
        data: state.data.concat(newUser)
      }));
    }
  }

  del(index) {
    let { data } = this.state;
    data.splice(index, 1);
    this.setState({
      data
    });
  }
  render() {
    return (
      <div>
        <form onSubmit={this.show}>
          <label>Login</label>
          <br />
          <input type="text" name="login" onChange={e => this.add(e)} />
          <br />
          <label>Password</label>
          <br />
          <input type="text" name="pass" onChange={e => this.add(e)} />
          <br />
          <input type="submit" value="Add" />
        </form>
        <table>
          {this.state.data.map((val, index) => (
            <BrowserRouter>
              <thead>
                <tr>
                  <th>ID</th>
                  <th>LOGIN</th>
                  <th>PASSWORD</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <Switch>
                    <NavLink to={"/single/" + index}>
                      <td key={index}>{index}</td>
                    </NavLink>
                    <Route exact path={"/single/" + index}>
                      <Single />
                    </Route>
                  </Switch>

                  <td>{val.login}</td>
                  <td>{val.pass}</td>
                </tr>
              </tbody>
              <input type="submit" value="X" onClick={() => this.del(index)} />
            </BrowserRouter>
          ))}
        </table>
      </div>
    );
  }
}

export default List;

Single.js

import React, { Component } from 'react';


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

    }

    render() {
        return (
            <div>
                //here i try to show id
            </div>
        )
    }

}

export default Single;

0 个答案:

没有答案