在功能组件中存储变量值

时间:2020-04-08 02:32:08

标签: javascript reactjs react-hooks

因此,在React类组件中,我可以轻松地添加一个属性:

EmailSender(Email const& email)
    : mEmail{ email }  // Initialize (construct) using the copy-constructor
{
    // Empty body
}

卸载/重新安装时,当然会重置此变量(因为它是该类的新实例)。功能组件似乎没有这么奢侈:

export default class Thing extends Component {
    constructor(props){
        super(props)

        this.hasRunQuery = false
    }

    handleClick = () => {
        this.hasRunQuery = true
    }

    render(){
        return (
            <button onClick={this.handleClick}>
                Click 
            </button>
        )
    }

如果卸载并重新安装上述组件,则let hasRunQuery = false export default () => { handleSubmit = () => { hasRunQuery = true } return ( <button onClick={handleSubmit}> Click </button> ) } 仍为true。如果该组件有10个实例,它们将以某种方式共享相同的变量。

hasRunQuery中存储所有属性的时间很短,是否有任何方法可以在函数组件中设置一旦卸载就不会保留其值的变量?

1 个答案:

答案 0 :(得分:1)

在功能组件中,这是通过useRef

实现的
export default () => {
    const hasRunQuery = useRef(false)

    const handleSubmit = () => {
        hasRunQuery.current = true
    }

    return (
        <button onClick={handleSubmit}>
            Click
        </button>
    )
}

有关更多信息,see the api documentation加上this section of the faq