reactjs - 在初始状态之后命名 useState 的当前状态,但使用当前状态值
问题描述
正如您在下面看到的,我正在从父组件调用isChecked道具。<Todo/>
我需要根据用户的点击来更改它的值,所以我正在使用“useState”并设置一个事件。问题是我无法将它发送到名为currentCheck的 API ,它需要被命名为isChecked以便我的 API 可以识别并保存新值。
Obs:我是 React 的新手,我只是在训练,所以这可能是一个愚蠢的问题,sry。
function Todo({ _id, text, isChecked }) {
const [currentCheck, setCurrentCheck] = useState(isChecked),
[icon, setIcon] = useState(ellipseOutline)
async function handleClick() {
if (currentCheck) {
setCurrentCheck(false)
setIcon(ellipseOutline)
return await api.put('/', { _id, currentCheck })
}
setCurrentCheck(true)
setIcon(checkmarkCircle)
return await api.put('/', { _id, currentCheck })
}
解决方案
据我了解你的问题。您的 API 请求看起来像{_id: 1, isChecked: true}
,您需要isChecked
属性而不是currentCheck
.
你可以这样做
function Todo({ _id, text, isChecked }) {
const [currentCheck, setCurrentCheck] = useState(isChecked),
[icon, setIcon] = useState(ellipseOutline)
async function handleClick() {
if (currentCheck) {
setCurrentCheck(false)
setIcon(ellipseOutline)
return await api.put('/', { _id, isChecked : currentCheck })
}
setCurrentCheck(true)
setIcon(checkmarkCircle)
return await api.put('/', { _id, isChecked : currentCheck })
}
这也可以写成
function Todo({ _id, text, isChecked }) {
const [currentCheck, setCurrentCheck] = useState(isChecked),
[icon, setIcon] = useState(ellipseOutline)
async function handleClick() {
setCurrentCheck((prevState) => !prevState);
setIcon(() => currentCheck ? ellipseOutline : checkmarkCircle);
return await api.put('/', { _id, isChecked : currentCheck })
}
推荐阅读
- reactjs - 在 React Bootstrap 表单中停止验证 React Form 组件中的一个字段
- go - 如何正确地从 exec Pod 流式传输日志
- r - 尝试计算相关矩阵时如何解释此错误的含义?
- ip - Windows 10 Command Prompt ADB over Wireless Network 中“无法连接”错误的解决方案
- javascript - 为什么不等于where子句查询需要在firestore中排序?
- ruby-on-rails - Friendly_id 没有出现在 Rails 上
- react-native - 默认测试在新的 React Native 0.59.10 中不起作用
- java - Bean 创建异常,实体管理器工厂错误
- postgresql - 为 postgres 初始设置脚本设置变量
- python - 在多个用户帐户上运行“botometer-python”脚本并保存到 CSV 时出现问题