繁体   English   中英

使用 useState 挂钩时如何访问 this.state?

[英]How do I access a this.state when using the useState hook?

我正在尝试发送我的组件的 state object。 I was using a class component and converted it to a function utilising useState() but now I can't access the state object using this.state .

我已经通过创建一个名为state的 object 来代替它,但我猜这不是最优雅的解决方案......

export default function Contact () {
    const [name, setName] = useState("")
    const [email, setEmail] = useState("")
    const [enquiryType, setEnquiryType] = useState("General Enquiry")
    const [message, setMessage] = useState("")

    const state = {
        name,
        email,
        enquiryType,
        message
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        console.log(state) // vs this.state
        var service_id = "default_service";
        var template_id = "message_template";
        var user_id = "user_[whatever]"
        emailjs.send(service_id, template_id, state, user_id); // vs this.state
    }

}

您已将 state 分解为 4 个不同的状态。 您也可以单独使用这些状态,但如果您想将这些状态合并到 1 个 object 中,我建议您研究useReducer钩子。 您可以阅读肯特 C。 多兹发帖进行比较。

如果我正确地关注了你的问题,你可以使用 useReducer 或者如果你想使用 useState,你可以试试这个方法:

const initialStates={...yourObject}
const [state,setState]=useState(initialStates)

然后将其传递为 state

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM