0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【React】TypeError: Assignment to constant variableの対処法

Posted at

症状

下記ソースを実行したときに、TypeError: Assignment to constant variableが発生してしまいました。 翻訳すると、「TypeError: 定数変数への代入」という内容でした。
エラー
TypeError: Assignment to constant variable
Hoge.jsx
import React, {Fragment, useEffect}  from 'react' ;

export const Hoge = () => {
    const hoge = ""
    useEffect(() => {
      value= "fuga"
    },[]);
    return (
        <Fragment>
            {/* #{hogeList } */}
        </Fragment>
    )
}

解決方法

定数に対して再度値を代入しようとしていたため、起きていたようです。 useEffect内で代入せず、useStateやuseReduverで値を管理するとよさそうです。
Hoge.jsx
import React, {Fragment, useEffect,useState}  from 'react' ;

export const Test = () => {
    const [value, setValue] = useState("initialState")

    useEffect(() => {
      setValue("fuga");
    },[]);
    return (
        <Fragment>
            {/* #{value} */}
        </Fragment>
    )
}

参考

https://www.javadrive.jp/javascript/var/index8.html
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?