sourcecode

상수 또는 읽기 전용 속성이므로 '상태'에 할당할 수 없습니다.

copyscript 2023. 3. 15. 19:52
반응형

상수 또는 읽기 전용 속성이므로 '상태'에 할당할 수 없습니다.

이 문제를 검색할 때 수정하는 질문만 찾을 수 있습니다.this.state사용하는 대신 방법 본체의 어딘가에서 직접this.setState()문제는 컨스트럭터에서 다음과 같이 시작 상태를 설정하고 싶다는 것입니다.

export default class Square extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      active: false
    };
  }

  public render() {
    ...
  }
}

앱이 시작되지 않고 다음 컴파일 오류가 발생합니다.

Cannot assign to 'state' because it is a constant or a read-only property

그리고 이것은 정의상React.Component다음과 같은 것이 있습니다.

readonly state: null | Readonly<S>;

그래서 어떻게 해야 할지 모르겠어요.JS의 공식 반응 튜토리얼은 다음을 직접 할당합니다.this.state컨스트럭터에서는 허용 가능한 패턴이라고 합니다만, TypeScript 에서는 이 방법을 알 수 없습니다.

롤백하기 전에(@torvin의 답변에서 제시된 바와 같이) https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26813#issuecomment-400795486에서 읽어보시기 바랍니다.

이것은 회귀를 의미하는 것이 아닙니다.해결책은state소유물로써.이전의 어프로치(설정)보다 좋다.state컨스트럭터에서)의 이유:

  • 더 이상 컨스트럭터가 필요 없습니다.
  • 상태를 초기화하는 것을 잊어서는 안 됩니다(현재 컴파일 시간 오류입니다).

예를 들어 다음과 같습니다.

type Props {}

type State {
  active: boolean
}

export default class Square extends React.Component<Props, State> {
  public readonly state: State = {
    active: false
  }

  public render() {
    //...
  }
}

또 다른 접근법:

type Props {}

const InitialState = {
  active: false
}

type State = typeof InitialState

export default class Square extends React.Component<Props, State> {
  public readonly state = InitialState

  public render() {
    //...
  }
}

이것은 최근의 변화인 것 같습니다.@types/reactcommit 542f3c0에서 도입되었습니다.Typescript는 파생된 컨스트럭터에서 부모의 읽기 전용 필드를 할당하는 것을 지원하지 않습니다.

이전 버전으로 롤백할 것을 권장합니다.@types/react. 버전16.4.2이 불행한 변경이 이루어지기 전 마지막이 될 것 같습니다.

버전을 고정하려면^당신의 안에서package.json:

"devDependencies": {
  ...
  "@types/react": "16.4.2",

또한 이 변경에 대한 논의는 에서 확인하시기 바랍니다.입력된 github 풀 요청 페이지

왜냐면state는 컴포넌트의 읽기 전용 속성으로 필드별로 설정할 수 없지만 다음 작업을 수행할 수 있습니다.

constructor(props: MyProps) {
  super(props);
  this.state = {
    // include properties here
  }
}

언급URL : https://stackoverflow.com/questions/51074355/cannot-assign-to-state-because-it-is-a-constant-or-a-read-only-property

반응형