React setState Delayを回避する方法は?

ジャン・パウロ・サモラ

私は一般的なReactsetState遅延の単純な問題に固執しています。現在、配列内のオブジェクトを子コンポーネント内の状態変数「newStud」に保存し、それを親コンポーネントに渡してフィルタリング機能に使用することで、オブジェクトを更新しようとしています。私の現在の問題は、私のサイトにエントリを2回送信した後にのみ、状態が完全に更新されることです。したがって、親コンポーネントのフィルター関数が渡される配列の読み取りを目的とする場合、最初の状態宣言が渡されるため、エラーがスローされます。私の質問は、更新の遅延を調整できる方法があるかどうかです。大きなコンポーネントをより小さな管理しやすいコンポーネントに分解することなく、その情報を入手できますか?

参考までに、子コンポーネントに使用しているコードを次に示します(この問題は「addTag」関数にあります)。

import React, {useState, useEffect} from 'react';
import './studentcard.css';

import { Tags } from '../Tags/tags.js';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlus } from '@fortawesome/free-solid-svg-icons';
import { faMinus } from '@fortawesome/free-solid-svg-icons';


export function StudentCard({student, upStuds}) {
  const [newStud, setNewStud] = useState({});
  const [clicked, setClicked] = useState(false);
  const [tag, setTag] = useState('');

  // switches boolean to opposite value for plus/minus icon display
  const onClick = () => {
    setClicked(!clicked);
  };

  // triggers the addTag function to push a tag to the array within the student object
  const onSubmit = async (e) => {
    e.preventDefault();
    
    await addTag(tag);
  };

  // captures the values being entered into the input 
  const onChange = (e) => {
    setTag(e.target.value);
  };

  // this pushes the tag state value into the array that is located in the student object being passed down from the parent component
  // it is meant to save the new copy of the "student" value in "newStuds" state variable, and pass that into the callback func
  // ********** here is where I am experiencing my delay ************
  const addTag = () => {

    student.tags.push(tag);
    setNewStud({...student});
    upStuds(newStud);

    setTag('');
  };

  let scores;
  if (clicked !== false) {
   scores = <ul className='grades-list'>
      {student.grades.map((grade, index) => <li key={index} className='grade'>Test {(index + 1) + ':'}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{grade}%</li>)}
    </ul>;
  } 

  return (
    <div className='studentCard' >
      <div className='pic-and-text'>
        <img className='student-image' alt='' src={student.pic}></img>
        <section className='right-side'>
            <h3 id='names'>{student.firstName.toUpperCase() + ' ' + student.lastName.toUpperCase()}</h3>
            <h4 className='indent'>Email: {student.email}</h4>
            <h4 className='indent'>Company: {student.company}</h4>
            <h4 className='indent'>Skill: {student.skill}</h4>
            <h4 className='indent'>Average: {student.grades.reduce((a, b) => parseInt(a) + parseInt(b), 0) / student.grades.length}%</h4>
            {scores}
            <Tags student={student}/>
            <form className='tag-form' onSubmit={onSubmit}>
              <input className='tag-input' type='text' placeholder='Add a tag' onChange={onChange} value={tag}></input>
            </form>
        </section>
      </div>  
         <FontAwesomeIcon icon={clicked !== false ? faMinus : faPlus} className='icon' onClick={onClick}/>
    </div>
  )
};

そして、必要に応じて、更新された情報を受信しようとしている親コンポーネントがあります(子コンポーネントから情報をフェッチするために使用しているコールバック関数は「upStuds」と呼ばれます):

import React, {useState, useEffect} from 'react';
import './dashboard.css';

import {StudentCard} from '../StudentCard/studentcard';

import axios from 'axios';

export function Dashboard() {
    const [students, setStudents] = useState([]);
    const [search, setSearch] = useState('');
    const [tagSearch, setTagSearch] = useState('');

    useEffect(() => {
      const options = {
        method: 'GET',
        url: 'https://api.hatchways.io/assessment/students'
      };

      var index = 0;
      function genID() {
        const result = index;
        index += 1;

        return result;
      };

      axios.request(options).then((res) => {
        const students = res.data.students;
        const newData = students.map((data) => {
          const temp = data;

          temp["tags"] = [];
          temp["id"] = genID();
          return temp;
        });

        setStudents(newData);
      }).catch((err) => {
        console.log(err);
      });
    }, []);

    const onSearchChange = (e) => {
      setSearch(e.target.value);
    };

    const onTagChange = (e) => {
      setTagSearch(e.target.value);
    }; 
    
    // here is the callback function that is not receiving the necessary information on time
    const upStuds = (update) => {
      let updatedCopy =  students;

      updatedCopy.splice(update.id, 1, update);

      setStudents(updatedCopy);

    };

    // const filteredTagged = tagList.filter
  return (
    <div className='dashboard'>
      <input className='form-text1' type='text' placeholder='Search by name' onChange={onSearchChange}></input>
      <input className='form-text2' type='text' placeholder='Search by tag' onChange={onTagChange}></input>

      
      {students.filter((entry) => {
        const fullName = entry.firstName + entry.lastName;
        const fullNameWSpace = entry.firstName + ' ' + entry.lastName;
        if (search === '') {
          return entry;
        } else if (entry.firstName.toLowerCase().includes(search.toLowerCase()) || entry.lastName.toLowerCase().includes(search.toLowerCase()) 
        || fullName.toLowerCase().includes(search.toLowerCase()) || fullNameWSpace.toLowerCase().includes(search.toLowerCase())) {
          return entry;
        }
      }).map((entry, index) => {
        return (<StudentCard student={entry} key={index} upStuds={upStuds} />)
      })}
    </div>
  )
};

何か明確にする必要がある場合はお知らせください。助けてくれてありがとう!

ニコラスタワー
setNewStud({...student});
upStuds(newStud);

新しい状態をupStudsに送信する場合は、それを変数に割り当てて2回使用できます。

const newState = {...student};
setNewStud(newState);
upStuds(newState);

さらに、upStuds関数を変更する必要があります。現在、既存のstudents配列を変更しているため、setStudentsを設定してもレンダリングは発生しません。アレイをコピーして、コピーを編集する必要があります。

const upStuds = (update) => {
  let updatedCopy = [...students]; // <--- using spread operator to create a shallow copy
  updatedCopy.splice(update.id, 1, update);
  setStudents(updatedCopy);
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

TOP 一覧

  1. 1

    グラフからテーブルに条件付き書式を適用するにはどうすればよいですか?

  2. 2

    ソートされた検索、ターゲット値未満の数をカウント

  3. 3

    Unity:未知のスクリプトをGameObject(カスタムエディター)に動的にアタッチする方法

  4. 4

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  5. 5

    Ansibleで複数行のシェルスクリプトを実行する方法

  6. 6

    Reactでclsxを使用する方法

  7. 7

    tkinterウィンドウを閉じてもPythonプログラムが終了しない

  8. 8

    Windows 10 Pro 1709を1803、1809、または1903に更新しますか?

  9. 9

    Pythonを使用して同じ列の同じ値の間の時差を取得する方法

  10. 10

    PowerShellの分割ファイルへのヘッダーの追加

  11. 11

    Chromeウェブアプリのウェブビューの高さの問題

  12. 12

    BLOBストレージからデータを読み取り、Azure関数アプリを使用してデータにアクセスする方法

  13. 13

    Crashlytics:コンパイラー生成とはどういう意味ですか?

  14. 14

    GoDaddyでのCKEditorとKCfinderの画像プレビュー

  15. 15

    Windows 10の起動時間:以前は20秒でしたが、現在は6〜8倍になっています

  16. 16

    MLでのデータ前処理の背後にある直感

  17. 17

    モーダルダイアログを自動的に閉じる-サーバーコードが完了したら、Googleスプレッドシートのダイアログを閉じます

  18. 18

    reCAPTCHA-エラーコード:ユーザーの応答を検証するときの「missing-input-response」、「missing-input-secret」(POSTの詳細がない)

  19. 19

    STSでループプロセス「クラスパス通知の送信」のループを停止する方法

  20. 20

    ファイル内の2つのマーカー間のテキストを、別のファイルのテキストのセクションに置き換えるにはどうすればよいですか?

  21. 21

    ネットワークグラフで、ネットワークコンポーネントにカーソルを合わせたときに、それらを強調表示するにはどうすればよいですか?

ホットタグ

アーカイブ