表头不断显示其内容,而不是仅在获取时显示一次

时间:2019-05-21 09:18:47

标签: reactjs

我正在从API中获取一些数据,并且我在使用良好的旧表,没有什么花哨的地方,但是我意识到thead中的信息一直显示为所有获取的信息的标题。所以说ny thead有名字,我取了两个名字,它将显示两次。我不确定如何纠正此错误。我的反应很新

//usersget.js
import React, { Component } from "react";
import "./App.css";
import { Link } from "react-router-dom";
import { deleteUsers } from "./actions/appactions";
import Spinner from "./Spinner.gif";
import { authenticationService } from "./login";
import { handleResponse } from "./helpers/handle-response";
import { authcomponent } from "./authecomponent";
import { Role } from "./role";
import { BootstrapTable, TableHeaderColumn } from "react-bootstrap-table-next";

//import axios from "axios";

class UsersGet extends Component {
  //default state object
  _isMounted = false;
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false
    };
  }
  componentDidMount() {
    fetch("https://localhost:44341/api/users", {
      method: "GET",
      mode: "cors",
      headers: authcomponent()
    })
      .then(handleResponse)
      .then(res => res)
      .then(json => {
        console.log(`Given JSON is ${json}`);
        if (this._isMounted) {
          this.setState({ isLoaded: false });
        } else {
          this.setState({
            isLoaded: true,
            items: json
          });
        }
      });
    authenticationService.currentUser.subscribe(x =>
      this.setState({
        currentUser: x,
        isAdmin: x && x.role === Role.Admin,
        isUser1: x && x.role === Role.User1,
        isUser2: x && x.role === Role.User2,
        isUser3: x && x.role === Role.User3
      })
    );
  }
  componentWillUnmount() {
    this._isMounted = false;
  }
  onDelete(id) {
    deleteUsers(id)
      .then(data => {
        let users = this.state.items.filter(users => {
          return id !== users;
        });
        this.setState(state => {
          state.items = users;
          return state;
        }).bind(this);
      })
      .catch(err => {
        console.error("err", err);
      });
  }
  deleteHandler(i, e) {
    e.preventDefault();
    this.onDelete(this.state.items[i].id);
    window.location.reload();
  }
  logout() {
    authenticationService.logout();
    this.props.history.push("/");
    /*
    we can either have logout as an arrow function or like below bind it to the "this" variable
    */
    // this.context.router.history.push("/Login");
    // const link = <Link to="/Login" />;
    // return link;

    // return <Redirect to="/Login" />;
  }
  render() {
    // console.log(Spinner);
    //  let data;
    const {
      isLoaded,
      items,
      currentUser,
      isAdmin,
      isUser1,
      isUser2,
      isUser3
    } = this.state;
    if (!isLoaded) {
      //  return (data = <img data-src={require("./Spinner.gif")} />); // return <div>Loading...</div>;
      return (
        <div className="text-center">
          <img src={Spinner} alt="Spinner" />;
        </div>
      );

      //return <div>Loading...</div>;
      // return (data = <img data-src={require("../images/giphy.gif")} />); // return <div>Loading...</div>;
    } else {
      return (
        <div>
          {currentUser && (
            <nav className="navbar navbar-expand navbar-dark bg-dark">
              <div className="navbar-nav">
                <Link to="/Home" className="nav-item nav-link">
                  Home
                </Link>
                {isAdmin && (
                  <Link to="/users" className="nav-item nav-link">
                    Users
                  </Link>
                )}
                {(isUser1 || isUser3 || isAdmin) && (
                  <Link to="/business" className="nav-item nav-link">
                    Business Listing
                  </Link>
                )}
                {(isUser2 || isUser3 || isAdmin) && (
                  <Link to="/categories" className="nav-item nav-link">
                    Categories
                  </Link>
                )}
                <a
                  onClick={this.logout.bind(this)}
                  className="nav-item nav-link"
                >
                  Sign out
                </a>
              </div>
            </nav>
          )}
          <div className="App">
            <h1>Users</h1> <Link to="/users/create">Create</Link>
            <ul className="list-unstyled">
              {items.map((item, i) => (
                // you hsve to use the json output for item.item
                <li key={item.id} className="text-secondary">
                  <div className="text-center">
                    <table>
                      <tbody>
                        <tr>
                          <th className="xx">First Name</th>
                          <th className="xx">Last Name</th>
                          <th className="xx">User Name</th>
                          <th className="xx">Password</th>
                          <th className="xx">Role</th>
                        </tr>
                        <tr className="mr-3">
                          <td>{item.firstName}</td>
                          <td>{item.lastName}</td>
                          <td>{item.userName}</td>
                          <td>{item.password}</td>
                          <td>{item.role}</td>
                          <td>
                            {" "}
                            <Link
                              to={`/users/update/${item.id}`}
                              className="m-3"
                            >
                              Update
                            </Link>
                            <button
                              onClick={this.deleteHandler.bind(this, i)}
                              onDelete={this.onDelete.bind(this)}
                              className="btn btn-danger btn-sm .ml-2"
                            />
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                  <div className=" m-2" />
                </li>
              ))}
            </ul>
          </div>
        </div>
      );
    }
  }
}

export default UsersGet;

1 个答案:

答案 0 :(得分:0)

将items.map((item,i)=>移至下一行的tr,如下所示,

 //usersget.js
    import React, { Component } from "react";
    import "./App.css";
    import { Link } from "react-router-dom";
    import { deleteUsers } from "./actions/appactions";
    import Spinner from "./Spinner.gif";
    import { authenticationService } from "./login";
    import { handleResponse } from "./helpers/handle-response";
    import { authcomponent } from "./authecomponent";
    import { Role } from "./role";
    import { BootstrapTable, TableHeaderColumn } from "react-bootstrap-table-next";

    //import axios from "axios";

    class UsersGet extends Component {
      //default state object
      _isMounted = false;
      constructor(props) {
        super(props);
        this.state = {
          items: [],
          isLoaded: false
        };
      }
      componentDidMount() {
        fetch("https://localhost:44341/api/users", {
          method: "GET",
          mode: "cors",
          headers: authcomponent()
        })
          .then(handleResponse)
          .then(res => res)
          .then(json => {
            console.log(`Given JSON is ${json}`);
            if (this._isMounted) {
              this.setState({ isLoaded: false });
            } else {
              this.setState({
                isLoaded: true,
                items: json
              });
            }
          });
        authenticationService.currentUser.subscribe(x =>
          this.setState({
            currentUser: x,
            isAdmin: x && x.role === Role.Admin,
            isUser1: x && x.role === Role.User1,
            isUser2: x && x.role === Role.User2,
            isUser3: x && x.role === Role.User3
          })
        );
      }
      componentWillUnmount() {
        this._isMounted = false;
      }
      onDelete(id) {
        deleteUsers(id)
          .then(data => {
            let users = this.state.items.filter(users => {
              return id !== users;
            });
            this.setState(state => {
              state.items = users;
              return state;
            }).bind(this);
          })
          .catch(err => {
            console.error("err", err);
          });
      }
      deleteHandler(i, e) {
        e.preventDefault();
        this.onDelete(this.state.items[i].id);
        window.location.reload();
      }
      logout() {
        authenticationService.logout();
        this.props.history.push("/");
        /*
        we can either have logout as an arrow function or like below bind it to the "this" variable
        */
        // this.context.router.history.push("/Login");
        // const link = <Link to="/Login" />;
        // return link;

        // return <Redirect to="/Login" />;
      }
      render() {
        // console.log(Spinner);
        //  let data;
        const {
          isLoaded,
          items,
          currentUser,
          isAdmin,
          isUser1,
          isUser2,
          isUser3
        } = this.state;
        if (!isLoaded) {
          //  return (data = <img data-src={require("./Spinner.gif")} />); // return <div>Loading...</div>;
          return (
            <div className="text-center">
              <img src={Spinner} alt="Spinner" />;
            </div>
          );

          //return <div>Loading...</div>;
          // return (data = <img data-src={require("../images/giphy.gif")} />); // return <div>Loading...</div>;
        } else {
          return (
            <div>
              {currentUser && (
                <nav className="navbar navbar-expand navbar-dark bg-dark">
                  <div className="navbar-nav">
                    <Link to="/Home" className="nav-item nav-link">
                      Home
                    </Link>
                    {isAdmin && (
                      <Link to="/users" className="nav-item nav-link">
                        Users
                      </Link>
                    )}
                    {(isUser1 || isUser3 || isAdmin) && (
                      <Link to="/business" className="nav-item nav-link">
                        Business Listing
                      </Link>
                    )}
                    {(isUser2 || isUser3 || isAdmin) && (
                      <Link to="/categories" className="nav-item nav-link">
                        Categories
                      </Link>
                    )}
                    <a
                      onClick={this.logout.bind(this)}
                      className="nav-item nav-link"
                    >
                      Sign out
                    </a>
                  </div>
                </nav>
              )}
              <div className="App">
                <h1>Users</h1> <Link to="/users/create">Create</Link>
                <ul className="list-unstyled">
                  <li className="text-secondary">
        <div className="text-center">
            <table>
                <tbody>
                    <tr>
                        <th className="xx">First Name</th>
                        <th className="xx">Last Name</th>
                        <th className="xx">User Name</th>
                        <th className="xx">Password</th>
                        <th className="xx">Role</th>
                    </tr>
                    {items.map((item, i) => (
                    <tr className="mr-3" key={item.id}>
                        <td>{item.firstName}</td>
                        <td>{item.lastName}</td>
                        <td>{item.userName}</td>
                        <td>{item.password}</td>
                        <td>{item.role}</td>
                        <td>
                            {" "}
                            <Link to={`/users/update/${item.id}`}
                                  className="m-3">
                            Update
                            </Link>
                            <button onClick={this.deleteHandler.bind(this, i)}
                                    onDelete={this.onDelete.bind(this)}
                                    className="btn btn-danger btn-sm .ml-2" />
                        </td>
                    </tr>
                    ))}
                </tbody>
            </table>
        </div>
        <div className=" m-2" />
    </li>  
                </ul>
              </div>
            </div>
          );
        }
      }
    }

    export default UsersGet;