首页 > 解决方案 > 如何将我的代码 ( this.state ) 转换为 useState()?

问题描述

我需要将以下代码转换为无状态功能组件,而不使用类。不幸的是,我不太擅长将基于类的组件解释为功能组件,所以我不确定语法到底是什么。

class Example extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isOpen: true,
        };
  }

    render() {
        return (
            <IconSettings iconPath="/assets/icons">
                {this.state.isOpen ? (
                    <AlertContainer>
                        <Alert
                            dismissible
                            icon={<Icon category="utility" name="user" />}
                            labels={{
                                heading: 'Logged in as John Smith (johnsmith@acme.com).',
                                headingLink: 'Log out',
                            }}
                            onClickHeadingLink={() => {
                                console.log('Link clicked.');
                            }}
                            onRequestClose={() => {
                                this.setState({ isOpen: false });
                            }}
                        />
                    </AlertContainer>
                ) : null}
            </IconSettings>
        );
    }
}

标签: reactjs

解决方案


这是正确的使用方法useState,如果您使用,redux您可以将其集成useSelector以获得初始状态。

这里的例子:

import React, { useState } from 'react'

function Example() { // or function Example(props) { , if you need to pass props to the component
    
    const [isOpen, setOpen] = useState(true) // <-- initial state for "isOpen"

    const onRequestClose = () => {
        setOpen(false)
    }
    
    return (
        <>
        // ... code
        <SomeComponent
            onRequestClose={onRequestClose}
            // ... rest of code
        />
        // ... more code
        </>
    )
}

推荐阅读