簡體   English   中英

ReactJs 模態關閉后清除 state

[英]ReactJs clear state after modal close

我正在研究一個獲取()一些數據的模式。 當模態關閉然后重新打開時,它會在幾秒鍾內可視化舊數據,然后更新數據。

我想避免顯示舊數據,只是空字段。 該組件以 class 方式編寫,我有一個 componentDidUpdate - 我在其中執行 fetch()。

歡迎任何建議!

export class InfoCustomer extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        clientInfos: {},
        clientCards: {},
        clientSubcsriptions: {},
    }
}

componentDidUpdate(prevProps) {
    if (this.props.show && !prevProps.show) this.openDetail();
}

openDetail() {

    WGet("Customers/preview", { id: this.props.customerId })
        .then(response => {
            this.setState({ clientInfos: response.data })
            //  API tessere
            WGet("Cards/customer", { customerId: this.props.customerId })
                .then(response => {
                    this.setState({ clientCards: response.data });
                    //  API Abbonamenti
                    WGet("Authorizations/customers/subscriptions", { customerId: this.props.customerId })
                        .then(response => this.setState({ clientSubscriptions: response.data }))
                        .catch((error) => {
                        });
                })
                .catch((error) => {
                });
        })
        .catch((error) => {
            this.setState({ hasError: true, messageError: error.responseMessages });
        });
}

和回報:

 return (
        <WModalOperation show={this.props.show} title={customerFullName} maxWidth="md"
            buttons={
                <WiButton variant="ghost" onClick={() => handleOnClose()}>Chiudi</WiButton>}>

            <Grid container  spacing={2} sx={{ height: '100%', overflow: 'hidden' }} >

                {/*Avatar and name*/}
                <Grid item xs={3} sx={{ display: 'grid', height: '100%', maxHeight: '100%', placeSelf: 'center', flexFlow: 'column ' }}>

                    <Grid sx={{ display: 'flex', alignItems: 'center' }}>
                        <WiInitialName size='big' photo={clientInfos.profilePictureUrl} alt={clientInfos.firstName} />
                    </Grid>

                    <Grid sx={{ display: 'flex', alignContent: 'center', flexFlow: 'column wrap', justifyContent: 'space-around', pl: 1, mt: 2 }}>
                        <Grid sx={{ mb: 3, display: 'flex', justifyContent: 'center' }}><WiLabel >{customerFullName}</WicLabel> </Grid>
                    </Grid>

                </Grid>


                {/*4 cards with leftBorder $bool*/}
                <Grid item xs={3} sx={{ display: 'flex', flexFlow: 'column wrap', height: '100%', alignItems: 'stretch', flexGrow: '1', gap: '1em', maxHeight: maXHeight }}>
                    {col1ToRender.map((item, i) => <CardContainer key={i} color={leftBorderColor(col1ToRenderParams[i].value)} title={item} content={col1ToRenderParams[i].name} />)}
                </Grid>
                {/*4 cards with leftBorder $bool*/}
                <Grid item xs={3} sx={{ display: 'flex', flexFlow: 'column wrap', height: '100%', alignItems: 'stretch', flexGrow: '1', gap: '1em', maxHeight: maXHeight }}>
                    {col2ToRender.map((item, i) => <CardContainer key={i + 4} color={leftBorderColor(col2ToRenderParams[i].value)} title={item} content={col2ToRenderParams[i].name} />)}
                </Grid>
                {/*Customer packages*/}
                <Grid item xs={3} sx={{ display: 'flex', flexFlow: 'column ', height: '100%', maxHeight: '368px', overflowY: 'scroll', alignContent: 'center', mt: '16px' }}
                    style={hideScrollbar}                        >
                    {customePackages}
                </Grid>
            </Grid>
        </WiModalOperation>
    )
}

}

我這樣做了:

 const handleOnClose = () => {
        this.setState({
            clientCards: {},
            clientInfos: {},
            clientSubscriptions: {},
        })
        this.props.show = !this.props.show
    }

將 state 重置為空

因此,假設您正在使用 useState 掛鈎,您可以觸發另一組 state 並清空數據。

偽代碼示例

const MyComp () => {
  const [state, setState] = React.useState({});
  React.useEffect(() => {
   /** query logic **/
   setState(data);
  }, [])

  const handleClose = () => {
    /** default close logic **/
    setState({}) // setting empty state on close
  }
  
  return (
    <Popup>
      <CloseButton onClickClose={() => handleClose()}>
    </Popup>
  )
}

您可以讓父組件有條件地渲染它,而不是讓InfoCustomer組件始終從道具中呈現和顯示/隱藏。

像這樣:

class parentComp extends React.Component {
   *component logic*

   return (
      <div>
         {this.state.show && <InfoCustomer/>} 
      </div>
   )
}

這樣,當您關閉模式時,組件將被卸載,state 將被清除。 您必須重新處理InfoCustomer組件以不再使用componentDidUpdate而是使用componentDidMount來執行您的提取。

暫無
暫無

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

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