单击按钮后如何将来自mongodb的数据显示到reactjs? [英] How to display data coming from mongodb to reactjs after clicking the button?

查看:52
本文介绍了单击按钮后如何将来自mongodb的数据显示到reactjs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 express.js、mongodb、react.js 和 node.js 制作 React 项目.并尝试从在端口 5000 上运行的后端 api 获取数据.

当我使用 postman 检查 api 时,它正在工作.数据显示在浏览器的控制台中.此外,当我按下下面代码中给出的 Get 按钮时,它在浏览器上不起作用.但是我可以在浏览器的控制台中看到数组数据.

这是我的完整代码:

import React, { Component } from "react";进口 {形式,表单组,表单控件,控制标签,按钮来自反应引导";导入./App.css";import { stringify } from "querystring";类 App 扩展组件 {构造函数(道具){超级(道具);this.AddName = this.AddName.bind(this);this.AddContact = this.AddContact.bind(this);this.AddAge = this.AddAge.bind(this);this.state = {名称: "",接触: "",年龄: "",雇员: []};}添加名称(e) {this.setState({ name: e.target.value });}添加联系人(e) {this.setState({ 联系人: e.target.value });}添加年龄(e) {this.setState({ age: e.target.value });}componentWillMount() {fetch("http://localhost:5000/api/employees").then(res => res.json()).then(data => this.setState({员工:数据}));}使成为() {const employeeItem = this.state.employees.map(employee => (<div key={employee._id}><h3>{employee.name}</h3><p>{employee.contact}</p><p>{employee.age}</p>

));返回 (<div className="应用程序"><header className="App-header"><h1 className="App-title">员工列表</h1></标题><div className="布局"><表格><表单组><ControlLabel>名称:</ControlLabel><表单控件类型=文本"值={this.state.name}占位符=员工姓名"onChange={this.AddName}/><div><ControlLabel>联系人:</ControlLabel><表单控件类型=数字"值={this.state.contact}占位符=手机号码"onChange={this.AddContact}/>

<div><ControlLabel>年龄:</ControlLabel><表单控件类型=数字"值={this.state.age}占位符=年龄"onChange={this.AddAge}/>

</FormGroup><Button type="submit">添加</Button><Button onClick={() =>console.log({employeeItem })}>Get</Button><Button type="submit">删除</Button></表单>

);}}导出默认应用程序;

运行页面

解决方案

当您在 onClick 回调中尝试时,您无法呈现项目.您可以在获取项目后立即呈现它们,或者您可以使用 onClick 触发获取,或者您可以隐藏和显示项目.

立即渲染

const 员工 = [{ _id: 1, 姓名: "foo", 联系人: "abc", 年龄: 20 },{ _id: 2, 姓名: "bar", 联系人: "efg", 年龄: 30 },{ _id:3,姓名:baz",联系人:hij",年龄:40 }];const fakeRequest = () =>new Promise(resolve => setTimeout(() => resolve(employees), 1000));类 App 扩展了 React.Component {状态 = {雇员: []};componentDidMount() {fakeRequest().then(employees => this.setState({员工}));}使成为() {const 员工 = this.state.employees.map(employee => (<div style={{ border: "1px solid black" }} key={employee._id}><h3>姓名:{employee.name}</h3><p>联系人:{employee.contact}</p><p>{employee.age}</p>

));返回 (<div><p>数据将在一秒钟内自动获取.</p>{雇员}

);}}ReactDOM.render(, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root"></div>

点击按钮获取

const 员工 = [{ _id: 1, 姓名: "foo", 联系人: "abc", 年龄: 20 },{ _id: 2, 姓名: "bar", 联系人: "efg", 年龄: 30 },{ _id: 3, 姓名: "baz", 联系人: "hij", 年龄: 40 },];const fakeRequest = () =>新承诺(解决 =>setTimeout(() => resolve(员工), 1000));类 App 扩展了 React.Component {状态 = {雇员: [],};getEmployees = () =>假请求().then(employees => this.setState({员工}))使成为() {const 员工 = this.state.employees.map(employee => (<div style={{ border: "1px solid black"}} key={employee._id}><h3>姓名:{employee.name}</h3><p>联系人:{employee.contact}</p><p>{employee.age}</p>

));返回 (<div><p>点击按钮后将获取数据.</p><button onClick={this.getEmployees} >获取员工</button>{雇员}

);}}ReactDOM.render(, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root"></div>

显示/隐藏方法

const 员工 = [{ _id: 1, 姓名: "foo", 联系人: "abc", 年龄: 20 },{ _id: 2, 姓名: "bar", 联系人: "efg", 年龄: 30 },{ _id: 3, 姓名: "baz", 联系人: "hij", 年龄: 40 },];const fakeRequest = () =>新承诺(解决 =>setTimeout(() => resolve(员工), 1000));类 App 扩展了 React.Component {状态 = {雇员: [],showEmployees: 假,};componentDidMount() {假请求().then(employees => this.setState({员工}))}切换员工 = () =>this.setState( prevState => ({showEmployees: !prevState.showEmployees,}))使成为() {const { showEmployees } = this.state;const 员工 = this.state.employees.map(employee => (<div style={{ border: "1px solid black"}} key={employee._id}><h3>姓名:{employee.name}</h3><p>联系人:{employee.contact}</p><p>{employee.age}</p>

));返回 (<div><p>数据将在一秒钟内自动获取,但默认情况下会隐藏.单击按钮可切换此状态.</p><按钮onClick={this.toggleEmployees}>{显示员工?隐藏员工":显示员工"}{this.state.showEmployees &&雇员}

);}}ReactDOM.render(, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root"></div>

I am making react project using express.js, mongodb, react.js, and node.js. and trying to fetch data from backend api which is running on port 5000.

When I check the api using postman, it is working. And the data is showing in the browser's console. Also, when I press Get button as given in the code below, it doesn't work on the browser. But I'm able to see the array data in the browser's console.

<Button onClick={()=><li>{employeeItem}</li>}>Get</Button>

Here is my full code:

import React, { Component } from "react";
import {
  form,
  FormGroup,
  FormControl,
  ControlLabel,
  Button
} from "react-bootstrap";
import "./App.css";
import { stringify } from "querystring";

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

    this.AddName = this.AddName.bind(this);
    this.AddContact = this.AddContact.bind(this);
    this.AddAge = this.AddAge.bind(this);

    this.state = {
      name: "",
      contact: "",
      age: "",
      employees: []
    };
  }
  AddName(e) {
    this.setState({ name: e.target.value });
  }
  AddContact(e) {
    this.setState({ contact: e.target.value });
  }
  AddAge(e) {
    this.setState({ age: e.target.value });
  }

  componentWillMount() {
    fetch("http://localhost:5000/api/employees")
      .then(res => res.json())
      .then(data => this.setState({ employees: data }));
  }

  render() {
    const employeeItem = this.state.employees.map(employee => (
      <div key={employee._id}>
        <h3>{employee.name}</h3>
        <p>{employee.contact}</p>
        <p>{employee.age}</p>
      </div>
    ));
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Employee List</h1>
        </header>
        <div className="Layout">
          <form>
            <FormGroup>
              <ControlLabel>Name:</ControlLabel>
              <FormControl
                type="text"
                value={this.state.name}
                placeholder="Employee name"
                onChange={this.AddName}
              />
              <div>
                <ControlLabel>Contact:</ControlLabel>
                <FormControl
                  type="number"
                  value={this.state.contact}
                  placeholder="Mobile number"
                  onChange={this.AddContact}
                />
              </div>
              <div>
                <ControlLabel>Age:</ControlLabel>
                <FormControl
                  type="number"
                  value={this.state.age}
                  placeholder="Age"
                  onChange={this.AddAge}
                />
              </div>
            </FormGroup>
            <Button type="submit">Add</Button>
            <Button onClick={() => console.log({ employeeItem })}>Get</Button>
            <Button type="submit">Delete</Button>
          </form>
        </div>
      </div>
    );
  }
}

export default App;

on running page

解决方案

You can't render an item as you are trying inside an onClick callback. You can render the items immediately after fetched them or you can trigger with an onClick the fetch or you can hide and show the items.

Immediately rendering

const employees = [
  { _id: 1, name: "foo", contact: "abc", age: 20 },
  { _id: 2, name: "bar", contact: "efg", age: 30 },
  { _id: 3, name: "baz", contact: "hij", age: 40 }
];

const fakeRequest = () =>
  new Promise(resolve => setTimeout(() => resolve(employees), 1000));

class App extends React.Component {
  state = {
    employees: []
  };

  componentDidMount() {
    fakeRequest().then(employees => this.setState({ employees }));
  }

  render() {
    const employees = this.state.employees.map(employee => (
      <div style={{ border: "1px solid black" }} key={employee._id}>
        <h3>Name: {employee.name}</h3>
        <p>Contact: {employee.contact}</p>
        <p>{employee.age}</p>
      </div>
    ));

    return (
      <div>
        <p>Data will be fetched in a second automatically.</p>
        {employees}
      </div>
    );
  }
}

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Get with a button click

const employees = [
  { _id: 1, name: "foo", contact: "abc", age: 20 },
  { _id: 2, name: "bar", contact: "efg", age: 30 },
  { _id: 3, name: "baz", contact: "hij", age: 40 },
];

const fakeRequest = () => new Promise( resolve =>
  setTimeout( () => resolve( employees ), 1000)
);

class App extends React.Component {
  state = {
    employees: [],
  };

  getEmployees = () =>
    fakeRequest()
      .then(employees => this.setState({ employees }))

  render() {
    const employees = this.state.employees.map(employee => (
      <div style={{ border: "1px solid black"}} key={employee._id}>
        <h3>Name: {employee.name}</h3>
        <p>Contact: {employee.contact}</p>
        <p>{employee.age}</p>
      </div>
    ));

    return (
      <div>
      <p>Data will be fetched after the button click.</p>
      <button onClick={this.getEmployees} >Get Employees</button>
      {employees}
      </div>
    );
  }
}

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Show/hide method

const employees = [
  { _id: 1, name: "foo", contact: "abc", age: 20 },
  { _id: 2, name: "bar", contact: "efg", age: 30 },
  { _id: 3, name: "baz", contact: "hij", age: 40 },
];

const fakeRequest = () => new Promise( resolve =>
  setTimeout( () => resolve( employees ), 1000)
);

class App extends React.Component {
  state = {
    employees: [],
    showEmployees: false,
  };
    
  componentDidMount() {
    fakeRequest()
      .then(employees => this.setState({ employees }))
  }

  toggleEmployees = () => this.setState( prevState => ({
    showEmployees: !prevState.showEmployees,
  }))

  render() {
    const { showEmployees } = this.state;
    const employees = this.state.employees.map(employee => (
      <div style={{ border: "1px solid black"}} key={employee._id}>
        <h3>Name: {employee.name}</h3>
        <p>Contact: {employee.contact}</p>
        <p>{employee.age}</p>
      </div>
    ));

    return (
      <div>
      <p>Data will be fethced automatically in a second but will be hidden by default. Button click toggles this state.</p>
      <button
        onClick={this.toggleEmployees}
      >
        {
          showEmployees ? "Hide Employees" : "Show Employees"
        }
      </button>
      {this.state.showEmployees && employees}
      </div>
    );
  }
}

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

这篇关于单击按钮后如何将来自mongodb的数据显示到reactjs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆