React三元运算符条件渲染语法问题:内容直接显示未生效
React条件渲染与状态更新问题解决
1. 三元运算符的正确语法
你当前的代码只是把表达式作为字符串直接渲染,React中要在JSX内执行JavaScript表达式,必须用**花括号{}**包裹。正确写法如下:
<Typography fontWeight="bold"> {isDeleted ? 'Successfully Deleted' : 'Hello User'} </Typography>
2. 修复deleteUser函数的错误
你的deleteUser函数存在两处问题:
- 错误调用
isDeleted(true):isDeleted是状态变量,并非更新状态的方法,修改状态必须使用setIsDeleted - axios.post的请求体传空数组可能不符合后端预期,若无请求体可传空对象
{}
修复后的函数:
const deleteUser = () => { axios.post("http://localhost:5000/delete", {}) .then((resp) => { // 假设后端返回的resp.data是布尔值true/false setIsDeleted(resp.data); }) .catch((err) => { // 建议添加错误处理,避免请求失败无反馈 console.error('删除失败:', err); }); };
3. 完整示例代码
整合后的组件片段:
import { useState } from 'react'; import { Box, Button, Typography } from '@mui/material'; import axios from 'axios'; const YourComponent = () => { const [isDeleted, setIsDeleted] = useState(false); const deleteUser = () => { axios.post("http://localhost:5000/delete", {}) .then((resp) => { setIsDeleted(resp.data); }) .catch((err) => { console.error('删除失败:', err); }); }; return ( <div> <Box> <Button sx={{ padding: "10px 20px" }} onClick={deleteUser} > Delete User </Button> </Box> <Typography fontWeight="bold"> {isDeleted ? 'Successfully Deleted' : 'Hello User'} </Typography> </div> ); }; export default YourComponent;
内容的提问来源于stack exchange,提问作者Didi
相关产品推荐
相关产品推荐

