1

I have a piece of code like this.

Modal.confirm({
    tilte: "title",
    content: (
        <>
            <input onChange={
                () => this.setState({ A: true });
            }></input>
            
            this.state.A && <div>text</div>
        </>
    )
})

The purpose is that after the input changes, <div>text</div> will be displayed, but it is found that state A cannot be obtained in time after the change, resulting in the content in div not being displayed. How can I modify it? ?

Zego Tech
  • 21
  • 4

1 Answers1

0

Question: You are using imperative (Modal.confirm) to display the Modal, and the state change does not trigger the Modal to re-render. solution:

Modal can be displayed declaratively, for example:

class Test extends React.Component {
  state = {
 A: false,
 visible: false
  };
  handleClick = () => {
 this.setState({ visible: true });
  };
  render() {
 const { visible } = this.state;
 return (
   <>
     <Button onClick={this.handleClick}>Show Modal</Button>
     <Modal
       visible={visible}
       onCancel={() => this.setState({ visible: false })}
     >
       <input onChange={() => this.setState({ A: true })}></input>
       {this.state.A && <div>text</div>}
     </Modal>
   </>
 );
  }
}

Extract the content displayed by Modal.confirm into a component

class ConfirmContent extends React.Component {
  state = {
 A: false
  };
  render() {
 return (
   <>
     <input onChange={() => this.setState({ A: true })}></input>
     {this.state.A && <div>text</div>}
   </>
 );
  }
}

//
Modal.confirm({
  tilte: "title",
  content: <ConfirmContent />
});
//

Root cause: The update granularity of React is a fiber tree, such an imperative method often recreates a fiber tree (internally it will call createRoot, or ReactDom.render), your question That's when the update operation is triggered with a fiber on fiber tree1 (the fiber tree you created yourself in App.tsx), not with fiber on fiber2 Update (the fiber tree you created with confirm), a component corresponds to a fiber, they belong to that fiber tree after they are passed a createRoot or ReactDom.renders

Kan Robert
  • 259
  • 1
  • 10