首页 > 解决方案 > 在初始状态之后命名 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 })
    }

标签: reactjsreact-hooks

解决方案


据我了解你的问题。您的 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 })
    }


推荐阅读