在初始状态之后命名useState的当前状态,但使用当前状态值

时间:2020-03-01 20:55:23

标签: reactjs react-hooks

如下所示,我从<Todo/>父组件中调用 isChecked 道具。我需要根据用户的点击更改它的值,因此我正在使用“ useState”并设置一个事件。问题是我无法将其发送到名为 currentCheck 的API,它需要再次命名为 isChecked ,这样我的API才能识别并保存新值。 / p>

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

2 个答案:

答案 0 :(得分: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 })
    }

答案 1 :(得分:0)

我认为您应按以下方式编写代码:

import tkinter
import tkinter.ttk

win = tkinter.Tk()
win.geometry('600x600')

frame = tkinter.Frame(win, bg='red', height=300)
frame.grid(row=0, column=0, sticky='ew')
win.grid_columnconfigure(0,weight=1)

win.mainloop()

请对其进行测试,并在评论中写下您的反馈意见