【问题标题】:Name useState's current state after the initial state, but with the current state value在初始状态之后命名 useState 的当前状态,但使用当前状态值
【发布时间】:2020-06-14 05:00:22
【问题描述】:

如下所示,我从 <Todo/> 父组件调用 isChecked 属性。我需要根据用户的点击来更改它的值,所以我正在使用“useState”并设置一个事件。问题是我无法将它发送到名为 currentCheck 的 API,它需要再次命名为 isChecked 以便我的 API 可以识别并保存新值。

Obs:我是 React 新手,我只是在训练,所以这可能是一个愚蠢的问题,抱歉。

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 })
    }

【问题讨论】:

  • 可以在匿名对象中命名key。 return await api.put('/', { _id, isChecked: currentCheck })

标签: reactjs react-hooks


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我认为你应该编写如下代码:

    function Todo({ _id, text, isChecked }) {
         const [currentCheck, setCurrentCheck] = useState(isChecked),
                    [icon, setIcon] = useState(ellipseOutline)
    
         async function handleClick() {
              if (currentCheck) {
                  setCurrentCheck(preve => !preve)
                  setIcon(ellipseOutline)
                  return await api.put('/', { _id, isChecked: currentCheck })
              }
              setCurrentCheck(preve => !preve)
              setIcon(checkmarkCircle)
              return await api.put('/', { _id, isChecked: currentCheck })
         }
    

    请测试它并在评论中写下您的反馈

    【讨论】:

    • 实际上问题在于我将名为“currentCheck”而不是“isChecked”的东西传递给 API。如何将 currentCheck 值传递给名为 isChecked 的内容并发送到 API?
    猜你喜欢
    • 1970-01-01
    • 2018-09-29
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多