如何根据axios.post reactjs的响应显示Material-ui Alert

Rym*_*mrk 6 reactjs material-ui

目前,使用默认警报 alert(response.data.result). 为了让我的网站更漂亮,我想使用Material-ui Alert。https://material-ui.com/components/alert/

我的问题是我不知道如何从const.

这是我的代码。

function Test(){
const saveData=async() => {
    await axios.post('/API', passedParams)
    .then(response => {
      if(response.data.success === true)
        {
          alert(response.data.result)
        }
      else
        {
          alert(response.data.result)
          //<Alert severity='error'>{response.data.result}</Alert> tried to use this but nothing displayed
          }
     }).catch(error=>{
        alert(error)
     })

//content of modal
cosnt bodyInsert = (
<div>
    ...fields
    <Button onClick={()=>saveData()}>Save</Button>
</div>
)
return(
<div>
<Modal
   open = {modalInsert}
   onClose = {openCloseModalInsert}>
   {bodyInsert}
</Modal>
</div>
)
}
export default Test;
Run Code Online (Sandbox Code Playgroud)

希望得到您的考虑。谢谢。

小智 13

function Test(){
const saveData=async() => {
    const [alert, setAlert] = useState(false);
    const [alertContent, setAlertContent] = useState('');
    await axios.post('/API', passedParams)
    .then(response => {
      if(response.data.success === true)
        {
          setAlertContent(response.data.result);
          setAlert(true);
        }
      else
        {
          setAlertContent(response.data.result);
          setAlert(true);
        }
     }).catch(error=>{
        alert(error)
     })

//content of modal
cosnt bodyInsert = (
<div>
    ...fields
    <Button onClick={()=>saveData()}>Save</Button>
</div>
)
return(
<div>
{alert ? <Alert severity='error'>{alertContent}</Alert> : <></> }
<Modal
   open = {modalInsert}
   onClose = {openCloseModalInsert}>
   {bodyInsert}
</Modal>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)