useRef只读值仅在初始化时

时间:2019-07-20 02:35:41

标签: reactjs typescript

移动到功能性的React组件上,useRef似乎是镜像类级别变量的方式。考虑:

class Component extends React.Component<Props> {
    private readonly foo: Something<Props>

    constructor(props: Props) {
      super(props)
      this.foo = new Something<Props>(props)
    }
}

在这种情况下,无法重新分配foo的值。

const Component : React.FunctionComponent<Props> = (props: Props) => {
    const foo = useRef(new Something<Props>(props));
    return null;
};

在这种情况下,foo.current是可变的,因为useRef返回MutableRefObject。另外,它每次都会初始化,这是我不想要的。是否有内置的东西使它们不可变?

1 个答案:

答案 0 :(得分:2)

Hooks常见问题解答包含有关How to create expensive objects lazily的部分。您可以使用callback signature of useState()来达到预期的效果:

const Component : React.FunctionComponent<Props> = (props: Props) => {
    const [foo] = React.useState(() => new Something<Props>(props) as const);
    return null;
};
相关问题