Reactjs 按钮onClick事件不更新组件状态

Reactjs 按钮onClick事件不更新组件状态,reactjs,react-bootstrap,Reactjs,React Bootstrap,我正在使用显示删除确认模式 这是我的确认模型 import React from "react"; import PropTypes from "prop-types"; import Button from "@material-ui/core/Button"; import Modal from "react-bootstrap/lib/Modal"; import "./ConfirmationModal.scss"; class ConfirmationModal extends Re

我正在使用显示删除确认模式

这是我的确认模型

import React from "react";
import PropTypes from "prop-types";
import Button from "@material-ui/core/Button";
import Modal from "react-bootstrap/lib/Modal";
import "./ConfirmationModal.scss";

class ConfirmationModal extends React.PureComponent {
  render() {
    return (
      <Modal
        {...this.props}
        size="md"
        aria-labelledby="contained-modal-title-vcenter"
        centered
        className="confirmation-modal"
      >
        <Modal.Header closeButton />
        <Modal.Body>
          <h4>Are you sure you want to delete?</h4>
          <p>{`You are about to delete ${this.props.deleteItem}`}</p>
        </Modal.Body>
        <Modal.Footer>
          <Button className="cancel-btn btn" onClick={this.props.onHide}>
            {"No, Cancel"}
          </Button>
          <Button className="delete-btn btn" onClick={this.props.onDelete}>
            {"Yes, Delete"}
          </Button>
        </Modal.Footer>
      </Modal>
    );
  }
}

ConfirmationModal.propTypes = {
  onClick: PropTypes.func,
  onDelete: PropTypes.func,
  deleteItem: PropTypes.string
};

ConfirmationModal.defaultProps = {
  onClick: () => {},
  onDelete: () => {},
  deleteItem: null
};

export { ConfirmationModal as default };

这是调用它的页面,最终,我将把这个片段添加到GridCommandCell删除函数中,但为了简单起见,我创建了这个按钮

import React from "react";
import PropTypes from "prop-types";
import Button from "@material-ui/core/Button";
import { Grid, GridColumn as Column } from "@progress/kendo-react-grid";
import GridLoader from "../../../common/utils/grid-loader";
import GridCommandCell from "../../../common/grid-command-cell";

import ConfirmationModal from "../../../common/confirmation-modal";
import "./UserGrid.scss";

class UserGrid extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      modalShow: false,
      gridData: { data: [], total: 0 },
      dataState: {
        take: 10,
        skip: 0,
        filter: [],
        sort: [
          {
            field: "Id",
            dir: "desc"
          }
        ]
      }
    };

    this.grid = React.createRef();
  }

  dataRecieved = gridData => {
    this.setState(prevState => ({
      ...prevState,
      gridData
    }));
  };

  dataStateChanged = e => {
    const index = e.data.filter.filters.findIndex(x => x.field === "Role.Name");

    if (index >= 0) e.data.filter.filters[index].ignoreCase = true;

    this.setState(prevState => ({
      ...prevState,
      dataState: e.data
    }));
  };

  refresh = () => {
    this.grid.refresh();
  };

  render() {
    const result = (
      <div className="gridContent-grid">
        <Grid
          id="user-grid"
          filterable
          sortable
          pageable={{
            buttonCount: 5,
            info: false,
            type: "numeric",
            pageSizes: false,
            previousNext: false
          }}
          {...this.state.dataState}
          {...this.state.gridData}
          onDataStateChange={this.dataStateChanged}
        >
          <Column field="Id" filter="numeric" title="Id" />
          <Column field="FirstName" title="First Name" />
          <Column field="LastName" title="Last Name" />
          <Column field="Role.Name" title="Role" />
          <Column
            className="command-btn"
            width="100%"
            cell={props => {
              const commandCell = (
                <GridCommandCell
                  onEdit={() => this.props.onEdit(props.dataItem.Id)}
                  // I need to set the onDelete to on click, activate modal
                  // onDelete={() => this.props.onDelete(props.dataItem.Id)}
                  onClick={() => this.setState({ modalShow: true })}
                />
              );
              return commandCell;
            }}
            filterable={false}
            sortable={false}
          />
          <ConfirmationModal
            show={this.state.modalShow}
            onHide={() => this.setState({ modalShow: false })}
            // onDelete={() => this.props.onDelete(dataItem.Id)}
            // deleteItem={`${dataItem.FirstName} ${dataItem.LastName}`}
          />
        </Grid>
        <GridLoader
          url="/odata/users?$select=Id, FirstName, LastName&$expand=Role&count=true&"
          dataState={this.state.dataState}
          onDataRecieved={this.dataRecieved}
          ref={grid => {
            this.grid = grid;
          }}
        />
        <Button
          variant="contained"
          className="delete-btn btn"
          type="button"
          onClick={() => {
            console.log(this.state);
            () => this.setState({ modalShow: true });
            console.log(this.state);
          }}
        >
          <span className="button-label">Delete modal</span>
        </Button>
      </div>
    );

    return result;
  }
}

UserGrid.propTypes = {
  onEdit: PropTypes.func,
  onDelete: PropTypes.func
};

UserGrid.defaultProps = {
  onEdit: () => {},
  onDelete: () => {}
};

export { UserGrid as default };
我正试图通过记录的onClick事件更新模态的状态

通过这个按钮

       <Button
          variant="contained"
          className="delete-btn btn"
          type="button"
          onClick={() => {
            console.log(this.state);
            () => this.setState({ modalShow: true });
            console.log(this.state);
          }}
        >
          <span className="button-label">Delete modal</span>
        </Button>
但是,my console.log语句都返回modalShow:false

我不明白为什么在onClick事件之后状态不会更新


请帮忙。谢谢大家!

设置状态为异步

setState不会立即改变this.state,但会创建挂起的状态转换。调用此方法后访问this.state可能会返回现有值。无法保证对setState调用的同步操作,并且可能会对调用进行批处理以提高性能

这样做

this.setState({ modalShow: true });
// might give old values, as state hasn't been set yet.
console.log(this.state);
您的状态不会随着您的操作而更新=>this.setState{modalShow:true};将其更改为以下内容

console.log(this.state);
this.setState({ modalShow: true }, console.log(this.state)); // pass setstate a callback which will be executed after the state is set.
类应用程序扩展了React.Component{ 建造师{ 超级的 此.state={ 名称:'反应', modalShow:错误 }; } 渲染{ 回来

{ console.logthis.state; this.setState{modalShow:true},=>{ console.logthis.state; }; }}> 使用回调调用状态

{ console.logthis.state; this.setState{modalShow:true}; console.logthis.state; }}> 设定值后的初始状态

; } } ReactDOM.render,document.getElementById'root';
我浏览了你之前的问题,发现你不接受答案,请当有人用正确的答案回答你的问题时。点击他们答案旁边的勾号接受答案。@tenpeter谢谢你的建议。我不确定这条法令是否正确。一定会回去做的。