[当使用reactjs useState时出现错误

问题描述 投票:-1回答:1

我正在使用reactjs。我正在使用物料表通过可编辑表获取数据。但是我收到类似图片的错误,如何解决此错误?

我将useState用于表的编辑设置。请您为错误提供帮助吗?

我在接收数据时没有收到任何错误。我只在表上使用活动/非活动编辑。但const [,forceUpdate] = useState(false);const [data,setData] = useState(drBounty);

给行以错误。

错误和我的源代码的屏幕截图

enter image description here

 import React, { Component, useState } from "react";
 import withAuth from "../../components/helpers/withAuth";
 import AlertMessageBox from "../../components/helpers/AlertMessageBox";
 import { connect } from "react-redux";
 import { Button, Col, Row, Table, Input } from "reactstrap";
 import MaterialTable, { MTableEditRow } from "material-table";
 import icons from '@material-ui/core/Icon';
 import DeleteOutline from '@material-ui/icons/DeleteOutline';
 import Edit from '@material-ui/icons/Edit';


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

   this.state = {
   isLoaded: true,

   drBounty: [],
   drList: [],

   columns: [
{ title: 'Name', field: 'doctorName',
  cellStyle:{padding: "1px", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: "1px"},
  editComponent: (props) => (
    <Input
      type="text"
      placeholder={props.columnDef.title}
      defaultValue={props.value}
      onChange={(e) => props.onChange(
        this.setState({
          doctorName: e.target.value
        })
      )}
    />
  )
},

{ title: 'LastName', field: 'doctorLastName',
  cellStyle:{padding: "1px", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: "5px"},
  editComponent: (props) => (
    <Input
      type={"text"}
      placeholder={"Doktor soyadı"}
      defaultValue={props.value}
      onChange={(e) => props.onChange(
        this.setState({
          doctorLastName: e.target.value
        })
      )}
       />
      )
    }
   ]
 };

   this.getBountyList = this.getBountyList.bind(this);
 }



 async componentDidMount() {
 await fetch(
 `${this.domain}/api/user/groupusers?groupCode=`+ 
 this.props.account_profile.profile.profile.groupCode,
  {
     headers: {
     Authorization: `Bearer ${localStorage.getItem("id_token")}`,
     "Content-Type": "application/json"
   }
  }
  )
  .then(res => {
   if (res.ok) {
     return res.json();
   } else {
     return res.json().then(err => Promise.reject(err));
   }
  })
  .then(json => {
      console.log(json)
  })
  .catch(error => {
   console.log(error)
   return error;
  });
  }

 async getBountyList(id) {
 await fetch(`${this.domain}/api/bounty/list?groupCode=${this.props.account_profile.profile.profile.groupCode}&doctor=${id}`,{
 headers: {
  Authorization: `Bearer ${localStorage.getItem("id_token")}`,
  "Content-Type": "application/json"
}
 })
 .then(res => {
   console.log(res);
   if (res.ok) {
     return res.json();
   } else {
     return res.json().then(err => Promise.reject(err));
   }
 })
 .then(json => {
   console.log(json)
 })
 .catch(error => {
   console.log(error);
   return error;
 });
 }

 render() {
 const {isLoaded, drList, drBounty} = this.state;

 const [, forceUpdate] = useState(false);
 const [data, setData] = useState(drBounty);

 const isRowUpdating = (rowData, status) => {
 rowData.tableData.editing = status ? "update" : undefined;
 forceUpdate(status);
 };

if (!isLoaded) {
   return <div>Loading...</div>;
   } else {
return (
<div className={"animated fadeIn "}>



  <Row>
    <div> &nbsp; &nbsp; </div>

    <Col sm={{span:1, offset:0.9}}>

      <Table>
        <thead>
        <tr>
          <th width={"20"} />
          <th width={"50"}>Adı</th>
          <th width={"70"}>Soyadı</th>
        </tr>
        </thead>
        <tbody>
        {
          drList
            .map(item => (
              <tr key={item.id}>
                <td>
                  <Button
                    block
                    outline
                    color="info"
                    onClick={() => this.getBountyList(item.id)}
                  >
                    Aç
                  </Button>
                </td>

                <td>{item.first_name} </td>
                <td>{item.last_name}</td>

              </tr>
            ))}
        </tbody>
      </Table>

    </Col>


    &nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;


    <MaterialTable
      Icons={icons}
      style={{height: "50", width: "50"}}
      columns={ this.state.columns }
      data={ this.state.drBounty }


      actions={[
        rowData => ({
          icon: Edit,
          tooltip: "Edit row",
          onClick: (event, rowData) => {
            isRowUpdating(rowData, true);

            this.setState({
              id: rowData.id,
              user: rowData.user,
              doctor: rowData.doctor,
              doctorName: rowData.doctorName,
              doctorLastName: rowData.doctorLastName,
              totalBounty: rowData.totalBounty,
              description: rowData.description,
              customerName: rowData.customerName,
              bountyDate: rowData.bountyDate,
              createdDate: rowData.createdDate,
              groupCode: rowData.groupCode
            });

          }
        })
      ]}

      components={{
        EditRow: props => {
          const newRowData = {
            ...drBounty,        // *MUST INCLUDE tableData FROM ORIGINAL props.data!!*
            id: "DEFAULT VALUES", // <-- // Set whatever default data you want here
            doctorName: "ON EDIT"       // <-- // (or pull from state, etc.. whatever you want)
          };

          return (
            <MTableEditRow
              {...props}
              data={newRowData}
              onEditingCanceled={(mode, rowData) => {
                isRowUpdating(rowData, false);
              }}
              onEditingApproved={(mode, newData, oldRowData) => {
                const dataCopy = [...drBounty];
                const index = drBounty.indexOf(props.data);
                dataCopy[index] = newData;
                setData(dataCopy);
                isRowUpdating(props.data, false);
              }}
            />
          );
        }
      }}
    />
  </Row>
     </div>
    );
   }
  }
 }

 export default connect(withAuth( Bounty ));
reactjs react-native material-ui material
1个回答
0
投票

您正在尝试在useState()方法中使用挂钩(render())。挂钩只能在function components内部使用。但是,由于使用的是class component,因此不需要此挂钩。建议阅读:https://reactjs.org/docs/hooks-state.html


代替使用挂钩,您可以在class component中使用以下命令来实现相同的结果。让我们看一看:)

构造函数中的初始化状态

this.state = { foo: bar };

您已经做到了!

使用this.setState()更新状态

const [data, setData] = useState(drBounty);

成为..

this.setState({data:drBounty});

但是,您想更新在构造函数中设置的drBounty道具,因此您将需要更多类似这样的东西..

this.setState({drBounty:someData})

由于该prop是一个数组,您很可能希望使用当前数组来散布(...)该数据。

无状态的重新渲染

关于useState()的其他实现,您似乎想重新渲染而不对状态进行任何更新。

const [, forceUpdate] = useState(false);

但是,您只需要简单地使用...

this.render()

© www.soinside.com 2019 - 2024. All rights reserved.