收到错误TypeError:这是未定义的

时间:2019-08-12 06:18:24

标签: reactjs

我想打开引导程序模版,该模版位于函数Dashboard中,但是当我给出其状态$(document).ready(function() { $('#dataTable').DataTable( { "processing": true, "serverSide": true, "ajax": { "url": "${pageContext.request.contextPath}/api/list" "type": "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', }, "columns": [ { "data": "name " }, { "data": "surname" } ] }); }); 时,它给我的错误是未定义的,这里我添加了我的整个代码,有人可以检查我的代码吗告诉我为什么会出现这个错误,

this.state.show

2 个答案:

答案 0 :(得分:1)

我认为您混淆了各个组件。如果您计划创建一个名为Dashboard的组件,则无需将其嵌套在另一个组件(DashboardComponent)中,即可访问state。仪表板本身可以作为组件存在。

使用useState()钩子,这是React为功能组件集成的钩子,以便它们具有类似状态的行为。

此外,您似乎需要设置父级Modal和一个用于切换opened state的函数。查看有效的沙箱:https://codesandbox.io/s/sad-hoover-cp8f2

import React, { useState } from "react";
import { Modal, Form, Button } from "react-bootstrap";

function Dashboard() {
  const [show, setShow] = useState(false);
  return (
    <section>
      <button onClick={() => setShow(!show)}>Display modal</button>
      <Modal show={show}>
        <Modal.Dialog>
          <Modal.Header closeButton>
            <Modal.Title>Newsletter</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Form>
              <Form.Group controlId="formBasicEmail">
                <Form.Label>Email address</Form.Label>
                <Form.Control type="email" placeholder="Enter email" />
                <Form.Text className="text-muted">
                  We'll never share your email with anyone else.
                </Form.Text>
              </Form.Group>
            </Form>
          </Modal.Body>

          <Modal.Footer>
            <Button onClick={() => setShow(!show)} variant="secondary">
              Close
            </Button>
            <Button variant="primary">Save changes</Button>
          </Modal.Footer>
        </Modal.Dialog>
      </Modal>
    </section>
  );
}

答案 1 :(得分:1)

我认为您应该这样做:

export class DashboardComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        show : false,
    }
  }
  render(){
      return (
       <section>
         <Modal.Dialog show={this.state.show}>
         <Modal.Header closeButton>
           <Modal.Title>Newsletter</Modal.Title>
         </Modal.Header>
         <Modal.Body>
           <Form>
             <Form.Group controlId="formBasicEmail">
               <Form.Label>Email address</Form.Label>
               <Form.Control type="email" placeholder="Enter email" />
               <Form.Text className="text-muted">
                 We'll never share your email with anyone else.
               </Form.Text>
             </Form.Group>
           </Form>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary">Close</Button>
          <Button variant="primary">Save changes</Button>
        </Modal.Footer>
      </Modal.Dialog>
    </section>  
  }
}