簡體   English   中英

ReactJS:狀態更改時元素不會更新

[英]ReactJS: element isn't updated when state changes

我有一個像這樣設置的React組件:

export default class FormDialog extends React.Component {
  constructor(){
    super();
    this.state = {allowedToDelete: false};
  }
  onChange(event) {

    if (event.target.value.match(this.targetName)) {
      console.log("It's a match!");
      this.state = {allowedToDelete: true};
      console.log(this.state); 
    } else {
      this.state = {allowedToDelete: false};
    }
  }

  render() {
    const { profile, deleteUser, handleDialogClose, ...other } = this.props;
    this.targetName = `${profile.firstName} ${profile.lastName}`;
    console.log({...other})

    return (
      <Dialog {...other}>
        <DialogTitle id="form-dialog-title">Delete this user?</DialogTitle>
        <DialogContent>
          <DialogContentText>
            allowedToDelete: {String(this.state.allowedToDelete)}
          </DialogContentText>
          <TextField
            autoFocus
            margin="dense"
            id="name"
            label="User's Full Name"
            type="text"
            fullWidth
            onChange={this.onChange.bind(this)}
          />
        </DialogContent>
        <DialogActions>
          <Button variant="outlined" onClick={this.handleDialogClose} color="primary">
            Cancel
          </Button>
          <Button variant="outlined" onClick={this.deleteUser} disabled={!this.state.allowedToDelete} color="primary">
            Delete User! 
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
}

(我在這里使用material-ui的表單對話框組件)。

如上所述,系統提示用戶輸入要刪除的配置文件的全名; 如果名稱匹配,則“刪除用戶!” 按鈕應變為禁用狀態。

我的onChange()事件正在運行,因為當我輸入正確的名稱時,我看到It's a match! 在我的控制台中, this.state的日志顯示this.state.allowedToDelete === true

但是,我的渲染函數的allowedToDelete: {String(this.state.allowedToDelete)}以及按鈕的disabled={!this.state.allowedToDelete}均為false

我在這里做錯了什么? 我是React的新手,我對狀態的理解可能很困惑,但是我嘗試使用直接附加到此變量而不是狀態的變量來執行this ,但這也不起作用...

您需要調用setState 您可以在react docs中閱讀有關它的信息 這告訴反應組件觸發生命周期以顯示新狀態。

this.setState({allowedToDelete: false});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM