下記のような Chapter を react の setState で状態管理しています。
typescript
1type Question = { 2 title: string; 3 body: string; 4 answers: string[]; 5} 6 7 8type Chapter = { 9 title: string; 10 questions: Question[]; 11}
下記のように、chapters の中の questions に対して、map で TestQuestion
というコンポーネントを展開して表示しています(タイトルを示すぐらいのもの)。
react
1const Test = () => { 2 const [chapters, setChapters] = useState<Chapter[] | undefined>() 3 4 return ( 5 <div> 6 {chapters && chapters?.questions && chapters.questions.map(question => ( 7 <TestQuestion question={question} /> 8 ) 9 </div> 10 ) 11}
chapters(配列)の中の questions を下記のようなメソッドで変更したところ、chapters は変わっているのですが(コンソールで確認済み)、<TestQustion />
はレンダリングされず、困っております。
typescript
1// 更新処理 2const changeChapters = (index:number, newTitle:string) => { 3 let arr = [...chapters] 4 arr[index]["questions"]["title"] = newTitle 5 setChapters(arr) 6}
[...chapters]
を使い、配列を再生成?しているため、レンダリングされると思ったのですが、うまくいかず。。おそらく、階層が深い questions
を更新しているため、レンダリングの判定で 前回のオブジェクトと同じだと認識されているのではないかと思います。
このような、オブジェクトの中に配列を持ち、その中のオブジェクトを更新するケースに置いて、値を更新後にレンダリングさせるにはどうすれば良いでしょうか。
何卒よろしくお願いします。
chapters だけでなく、Chapter や Question も作り直す必要があります。
あと、arr[index]["questions"] は配列なので、もう一つ index が必要では。
あなたの回答
tips
プレビュー