ReactJS
Data objects
ReactでのCRUD操作入門: Parseを使用したデータ管理
10 分
react crud チュートリアル はじめに parse にデータを保存することは、 parse object parse object クラスを中心に構築されています。各 parse object parse object には、json 互換のデータのキーと値のペアが含まれています。このデータはスキーマレスであり、各 parse object parse object にどのキーが存在するかを事前に指定する必要はありません。必要なキーと値のペアを設定するだけで、バックエンドがそれを保存します。 アプリケーションのニーズに応じてデータ型を指定し、次のようなタイプを永続化することもできます。 数値 数値 , ブール値 ブール値 , 文字列 文字列 , 日付時刻 日付時刻 , リスト リスト , geopointers geopointers , そして オブジェクト オブジェクト として、保存する前に json にエンコードします。parse はまた、 ポインタ ポインタ と リレーション リレーション を使用して、リレーショナルデータを保存およびクエリすることをサポートしています。 このガイドでは、crud の例アプリを通じて基本的なデータ操作を実行する方法を学びます。これにより、react で parse サーバーデータベースからデータを作成、読み取り、更新、削除する方法が示されます。最初に、各 crud 操作のためのコンポーネント関数を作成し、後で完全な画面レイアウトで使用し、最終的に to do リストアプリを作成します。 前提条件 このチュートリアルを完了するには、次のものが必要です: 作成されたreactアプリと back4appに接続された このガイドで提供される画面レイアウトをテスト/使用したい場合は、次のものを設定する必要があります: ant design ant design ライブラリ 目標 parseを使用してreactで基本的なcrudアプリケーションを構築すること。 1 データオブジェクトの作成 parseデータベースでデータを管理する最初のステップは、データを持つことです。では、次に新しいインスタンスを作成する createtodo createtodo 関数を作成しましょう。この関数は “todo” サブクラスを持つ parse object parse object の新しいインスタンスを作成します。to doには、タスクを説明するタイトル( string string )と、タスクが完了しているかどうかを示すdone( boolean boolean )フィールドがあります。 javascript 1 const createtodo = async function () { 2 // this value comes from a state variable 3 const newtodotitlevalue = newtodotitle; 4 // creates a new todo parse object instance 5 let todo = new parse object('todo'); 6 todo set('title', newtodotitlevalue); 7 todo set('done', false); 8 // after setting the to do values, save it on the server 9 try { 10 await todo save(); 11 // success 12 alert('success! to do created!'); 13 // refresh to dos list to show the new one (you will create this function later) 14 readtodos(); 15 return true; 16 } catch (error) { 17 // error can be caused by lack of internet connection 18 alert(`error! ${error message}`); 19 return false; 20 }; 21 };1 const createtodo = async function () promise\<boolean> { 2 // this value comes from a state variable 3 const newtodotitlevalue string = newtodotitle; 4 // creates a new todo parse object instance 5 let todo parse object = new parse object('todo'); 6 todo set('title', newtodotitlevalue); 7 todo set('done', false); 8 // after setting the to do values, save it on the server 9 try { 10 await todo save(); 11 // success 12 alert('success! to do created!'); 13 // refresh to dos list to show the new one (you will create this function later) 14 readtodos(); 15 return true; 16 } catch (error any) { 17 // error can be caused by lack of internet connection 18 alert(`error! ${error message}`); 19 return false; 20 }; 21 }; データベースに todo todo テーブル(またはサブクラス)がまだ存在しない場合、parseは自動的にそれを作成し、また parse object parse object インスタンス内で設定された任意の列を追加します。これは parse object set() parse object set() メソッドを使用し、2つの引数を取ります:フィールド名と設定する値です。 2 データオブジェクトの読み取り データベースにいくつかのデータを作成した後、アプリケーションはサーバーからそれを読み取り、ユーザーに表示できるようになります。続けて、 readtodos readtodos 関数を作成してください。この関数は、 parse query parse query を実行し、結果を状態変数に格納します。 javascript 1 const readtodos = async function () { 2 // reading parse objects is done by using parse query 3 const parsequery = new parse query('todo'); 4 try { 5 let todos = await parsequery find(); 6 // be aware that empty or invalid queries return as an empty array 7 // set results to state variable 8 setreadresults(todos); 9 return true; 10 } catch (error) { 11 // error can be caused by lack of internet connection 12 alert(`error! ${error message}`); 13 return false; 14 }; 15 };1 const readtodos = async function () promise\<boolean> { 2 // reading parse objects is done by using parse query 3 const parsequery parse query = new parse query('todo'); 4 try { 5 let todos parse object\[] = await parsequery find(); 6 // be aware that empty or invalid queries return as an empty array 7 // set results to state variable 8 setreadresults(todos); 9 return true; 10 } catch (error any) { 11 // error can be caused by lack of internet connection 12 alert(`error! ${error message}`); 13 return false; 14 }; 15 }; 多くの制約と順序を使用してクエリに適用できますが、 parse query parse query クラスを使用して、今のところはこのシンプルなクエリに留まります。これは保存されたすべての todo todo オブジェクトを取得します。 3 データオブジェクトの更新 インスタンスを更新することは、新しいインスタンスを作成することに非常に似ていますが、この場合、以前に作成した parse object parse object を割り当ててから、新しい値を設定した後に保存する必要があります。 javascript 1 const updatetodo = async function (todoid, done) { 2 // create a new todo parse object instance and set todo id 3 let todo = new parse object('todo'); 4 todo set('objectid', todoid); 5 // set new done value and save parse object changes 6 todo set('done', done); 7 try { 8 await todo save(); 9 // success 10 alert('success! to do updated!'); 11 // refresh to dos list 12 readtodos(); 13 return true; 14 } catch (error) { 15 // error can be caused by lack of internet connection 16 alert(`error! ${error message}`); 17 return false; 18 }; 19 };1 const updatetodo = async function ( 2 todoid string, 3 done boolean, 4 ) promise\<boolean> { 5 // create a new todo parse object instance and set todo id 6 let todo parse object = new parse object('todo'); 7 todo set('objectid', todoid); 8 // set new done value and save parse object changes 9 todo set('done', done); 10 try { 11 await todo save(); 12 // success 13 alert('success! to do updated!'); 14 // refresh to dos list 15 readtodos(); 16 return true; 17 } catch (error any) { 18 // error can be caused by lack of internet connection 19 alert(`error! ${error message}`); 20 return false; 21 }; 22 }; この例のアプリはタスクリストを表しているので、あなたの更新関数は追加の引数、すなわち 完了 完了 値を取ります。これは特定のタスクが完了しているかどうかを表します。 4 データオブジェクトの削除 データオブジェクトを削除するには、 destroy() destroy() メソッドをそのオブジェクトを表す parse object parse object インスタンスで呼び出す必要があります。この操作は元に戻せないので注意してください。 javascript 1 const deletetodo = async function (todoid) { 2 // create a new todo parse object instance and set todo id 3 const todo = new parse object('todo'); 4 todo set('objectid', todoid); 5 // destroy should be called to delete a parse object 6 try { 7 await todo destroy(); 8 alert('success! to do deleted!'); 9 // refresh to dos list to remove this one 10 readtodos(); 11 return true; 12 } catch (error) { 13 // error can be caused by lack of internet connection 14 alert(`error ${error message}`); 15 return false; 16 }; 17 };1 const deletetodo = async function (todoid string) promise\<boolean> { 2 // create a new todo parse object instance and set todo id 3 let todo parse object = new parse object('todo'); 4 todo set('objectid', todoid); 5 // destroy should be called to delete a parse object 6 try { 7 await todo destroy(); 8 alert('success! to do deleted!'); 9 // refresh to dos list to remove this one 10 readtodos(); 11 return true; 12 } catch (error any) { 13 // error can be caused by lack of internet connection 14 alert(`error! ${error message}`); 15 return false; 16 }; 17 }; これで、これらの4つの関数を完全なコンポーネントで使用して、テストし、すべてのcrud操作が正しく機能していることを確認できます。 5 reactコンポーネントでのcrudの使用 ここに、スタイル付きユーザーインターフェース要素( ant design ant design を使用)、状態変数、およびcrud関数への呼び出しを含む完全なコンポーネントコードがあります。 todolist js/todolist tsx todolist js/todolist tsx というファイルに別のコンポーネントを作成する必要があります。あなたの src src ディレクトリに次のコードを含めるか、直接メインアプリケーションファイル( app js/app tsx app js/app tsx )に追加してください。 todolist js 1 import react, { usestate } from 'react'; 2 import parse from 'parse/dist/parse min js'; 3 import ' /app css'; 4 import { button, input, list } from 'antd'; 5 import { 6 checkoutlined, 7 closeoutlined, 8 plusoutlined, 9 redooutlined, 10 } from '@ant design/icons'; 11 12 export const todolist = () => { 13 // state variables 14 const \[readresults, setreadresults] = usestate(\[]); 15 const \[newtodotitle, setnewtodotitle] = usestate(''); 16 17 // functions used by the screen components 18 const createtodo = async function () { 19 // this value comes from a state variable 20 const newtodotitlevalue = newtodotitle; 21 // creates a new todo parse object instance 22 let todo = new parse object('todo'); 23 todo set('title', newtodotitlevalue); 24 todo set('done', false); 25 // after setting the to do values, save it on the server 26 try { 27 await todo save(); 28 // success 29 alert('success! to do created!'); 30 // refresh to dos list to show the new one (you will create this function later) 31 readtodos(); 32 return true; 33 } catch (error) { 34 // error can be caused by lack of internet connection 35 alert(`error! ${error message}`); 36 return false; 37 } 38 }; 39 40 const readtodos = async function () { 41 // reading parse objects is done by using parse query 42 const parsequery = new parse query('todo'); 43 try { 44 let todos = await parsequery find(); 45 // be aware that empty or invalid queries return as an empty array 46 // set results to state variable 47 setreadresults(todos); 48 return true; 49 } catch (error) { 50 // error can be caused by lack of internet connection 51 alert(`error! ${error message}`); 52 return false; 53 } 54 }; 55 56 const updatetodo = async function (todoid, done) { 57 // create a new to do parse object instance and set todo id 58 let todo = new parse object('todo'); 59 todo set('objectid', todoid); 60 // set new done value and save parse object changes 61 todo set('done', done); 62 try { 63 await todo save(); 64 // success 65 alert('success! to do updated!'); 66 // refresh todos list 67 readtodos(); 68 return true; 69 } catch (error) { 70 // error can be caused by lack of internet connection 71 alert(`error! ${error message}`); 72 return false; 73 } 74 }; 75 76 const deletetodo = async function (todoid) { 77 // create a new todo parse object instance and set todo id 78 let todo = new parse object('todo'); 79 todo set('objectid', todoid); 80 // destroy should be called to delete a parse object 81 try { 82 await todo destroy(); 83 alert('success! to do deleted!'); 84 // refresh to dos list to remove this one 85 readtodos(); 86 return true; 87 } catch (error) { 88 // error can be caused by lack of internet connection 89 alert(`error! ${error message}`); 90 return false; 91 } 92 }; 93 94 return ( 95 \<div> 96 \<div classname="header"> 97 \<img 98 classname="header logo" 99 alt="back4app logo" 100 src={ 101 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png' 102 } 103 /> 104 \<p classname="header text bold">{'react on back4app'}\</p> 105 \<p classname="header text">{'to do list'}\</p> 106 \</div> 107 \<div classname="container"> 108 \<div classname="flex between"> 109 \<h2 classname="list heading">todo list\</h2> 110 {/ to do read (refresh) button /} 111 \<button 112 type="primary" 113 shape="circle" 114 color={'#208aec'} 115 size={'default'} 116 onclick={readtodos} 117 icon={\<redooutlined />} 118 >\</button> 119 \</div> 120 \<div classname="new todo wrapper flex between"> 121 {/ todo create text input /} 122 \<input 123 value={newtodotitle} 124 onchange={(event) => setnewtodotitle(event target value)} 125 placeholder="new todo" 126 size="large" 127 /> 128 {/ todo create button /} 129 \<button 130 type="primary" 131 classname="create todo button" 132 color={'#208aec'} 133 size={'large'} 134 onclick={createtodo} 135 icon={\<plusoutlined />} 136 > 137 add 138 \</button> 139 \</div> 140 \<div> 141 {/ todo read results list /} 142 {readresults !== null && 143 readresults !== undefined && 144 readresults length > 0 && ( 145 \<list 146 datasource={readresults} 147 renderitem={(item) => ( 148 \<list item classname="todo item"> 149 \<p 150 classname={ 151 item get('done') === true 152 ? 'todo text done' 153 'todo text' 154 } 155 > 156 {item get('title')} 157 \</p> 158 \<div classname="flex row"> 159 {/ todo update button /} 160 {item get('done') !== true && ( 161 \<button 162 type="primary" 163 shape="circle" 164 classname="todo button" 165 onclick={() => updatetodo(item id, true)} 166 icon={ 167 \<checkoutlined classname="todo button icon done" /> 168 } 169 >\</button> 170 )} 171 {/ todo delete button /} 172 \<button 173 type="primary" 174 shape="circle" 175 classname="todo button" 176 onclick={() => deletetodo(item id)} 177 icon={ 178 \<closeoutlined classname="todo button icon remove" /> 179 } 180 >\</button> 181 \</div> 182 \</list item> 183 )} 184 /> 185 )} 186 \</div> 187 \</div> 188 \</div> 189 ); 190 }; todolist tsx 1 import react, { usestate, fc, reactelement } from 'react'; 2 import ' /app css'; 3 import { button, input, list } from 'antd'; 4 import { 5 checkoutlined, 6 closeoutlined, 7 plusoutlined, 8 redooutlined, 9 } from '@ant design/icons'; 10 const parse = require('parse/dist/parse min js'); 11 12 export const todolist fc<{}> = () reactelement => { 13 // state variables 14 const initialreadresults parse object\[] = \[]; 15 const \[readresults, setreadresults] = usestate(initialreadresults); 16 const \[newtodotitle, setnewtodotitle] = usestate(''); 17 18 // functions used by the screen components 19 const createtodo = async function () promise\<boolean> { 20 // this value comes from a state variable 21 const newtodotitlevalue string = newtodotitle; 22 // creates a new todo parse object instance 23 let todo parse object = new parse object('todo'); 24 todo set('title', newtodotitlevalue); 25 todo set('done', false); 26 // after setting the to do values, save it on the server 27 try { 28 await todo save(); 29 // success 30 alert('success! to do created!'); 31 // refresh to dos list to show the new one (you will create this function later) 32 readtodos(); 33 return true; 34 } catch (error any) { 35 // error can be caused by lack of internet connection 36 alert('error!' + error message); 37 return false; 38 } 39 }; 40 41 const readtodos = async function () promise\<boolean> { 42 // reading parse objects is done by using parse query 43 const parsequery parse query = new parse query('todo'); 44 try { 45 let todos parse object\[] = await parsequery find(); 46 // be aware that empty or invalid queries return as an empty array 47 // set results to state variable 48 setreadresults(todos); 49 return true; 50 } catch (error any) { 51 // error can be caused by lack of internet connection 52 alert('error!' + error message); 53 return false; 54 } 55 }; 56 57 const updatetodo = async function (todoid string, done boolean) promise\<boolean> { 58 // create a new to do parse object instance and set todo id 59 let todo parse object = new parse object('todo'); 60 todo set('objectid', todoid); 61 // set new done value and save parse object changes 62 todo set('done', done); 63 try { 64 await todo save(); 65 // success 66 alert('success! to do updated!'); 67 // refresh todos list 68 readtodos(); 69 return true; 70 } catch (error any) { 71 // error can be caused by lack of internet connection 72 alert('error!' + error message); 73 return false; 74 } 75 }; 76 77 const deletetodo = async function (todoid string) promise\<boolean> { 78 // create a new todo parse object instance and set todo id 79 let todo parse object = new parse object('todo'); 80 todo set('objectid', todoid); 81 // destroy should be called to delete a parse object 82 try { 83 await todo destroy(); 84 alert('success! to do deleted!'); 85 // refresh to dos list to remove this one 86 readtodos(); 87 return true; 88 } catch (error any) { 89 // error can be caused by lack of internet connection 90 alert('error!' + error message); 91 return false; 92 } 93 }; 94 95 return ( 96 \<div> 97 \<div classname="header"> 98 \<img 99 classname="header logo" 100 alt="back4app logo" 101 src={ 102 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png' 103 } 104 /> 105 \<p classname="header text bold">{'react on back4app'}\</p> 106 \<p classname="header text">{'to do list'}\</p> 107 \</div> 108 \<div classname="container"> 109 \<div classname="flex between"> 110 \<h2 classname="list heading">todo list\</h2> 111 {/ to do read (refresh) button /} 112 \<button 113 type="primary" 114 shape="circle" 115 color={'#208aec'} 116 onclick={readtodos} 117 icon={\<redooutlined />} 118 >\</button> 119 \</div> 120 \<div classname="new todo wrapper flex between"> 121 {/ todo create text input /} 122 \<input 123 value={newtodotitle} 124 onchange={(event {target {value string}}) => setnewtodotitle(event target value)} 125 placeholder="new todo" 126 size="large" 127 /> 128 {/ todo create button /} 129 \<button 130 type="primary" 131 classname="create todo button" 132 color={'#208aec'} 133 size={'large'} 134 onclick={createtodo} 135 icon={\<plusoutlined />} 136 > 137 add 138 \</button> 139 \</div> 140 \<div> 141 {/ todo read results list /} 142 {readresults !== null && 143 readresults !== undefined && 144 readresults length > 0 && ( 145 \<list 146 datasource={readresults} 147 renderitem={(item parse object) => ( 148 \<list item classname="todo item"> 149 \<p 150 classname={ 151 item get('done') === true 152 ? 'todo text done' 153 'todo text' 154 } 155 > 156 {item get('title')} 157 \</p> 158 \<div classname="flex row"> 159 {/ todo update button /} 160 {item get('done') !== true && ( 161 \<button 162 type="primary" 163 shape="circle" 164 classname="todo button" 165 onclick={() => updatetodo(item id, true)} 166 icon={ 167 \<checkoutlined classname="todo button icon done" /> 168 } 169 >\</button> 170 )} 171 {/ todo delete button /} 172 \<button 173 type="primary" 174 shape="circle" 175 classname="todo button" 176 onclick={() => deletetodo(item id)} 177 icon={ 178 \<closeoutlined classname="todo button icon remove" /> 179 } 180 >\</button> 181 \</div> 182 \</list item> 183 )} 184 /> 185 )} 186 \</div> 187 \</div> 188 \</div> 189 ); 190 }; また、これらのcssスタイルをあなたの app css app css ファイルの最後に追加してください 1 / / 2 / your other styles / 3 4 / back4app guide styles / 5 6 html { 7 box sizing border box; 8 outline none; 9 overflow auto; 10 } 11 12 , 13 before, 14 after { 15 margin 0; 16 padding 0; 17 box sizing inherit; 18 } 19 20 h1, 21 h2, 22 h3, 23 h4, 24 h5, 25 h6 { 26 margin 0; 27 } 28 29 p { 30 margin 0; 31 } 32 33 body { 34 margin 0; 35 background color #fff; 36 } 37 38 container { 39 width 100%; 40 max width 600px; 41 margin auto; 42 padding 20px 0; 43 } 44 45 wrapper { 46 width '90%'; 47 align self 'center'; 48 } 49 50 header { 51 align items center; 52 padding 25px 0; 53 background color #208aec; 54 } 55 56 header logo { 57 height 55px; 58 margin bottom 20px; 59 object fit contain; 60 } 61 62 header text bold { 63 margin bottom 3px; 64 color rgba(255, 255, 255, 0 9); 65 font size 16px; 66 font weight bold; 67 } 68 69 header text { 70 color rgba(255, 255, 255, 0 9); 71 font size 15px; 72 } 73 74 flex row { 75 display flex; 76 } 77 78 flex between { 79 display flex; 80 align items center; 81 justify content space between; 82 } 83 84 list heading { 85 font weight bold; 86 } 87 88 new todo wrapper { 89 margin top 20px; 90 margin bottom 10px; 91 } 92 93 new todo wrapper > input { 94 margin right 20px; 95 } 96 97 todo item { 98 border bottom width 1; 99 border bottom color 'rgba(0, 0, 0, 0 12)'; 100 } 101 102 todo text { 103 font size 15px; 104 } 105 106 todo text done { 107 color rgba(0, 0, 0, 0 3); 108 font size 15px; 109 text decoration line line through; 110 } 111 112 todo button { 113 width 32px; 114 height 32px; 115 margin left 5px; 116 background color transparent; 117 border radius 50px; 118 border none; 119 cursor pointer; 120 } 121 122 todo button\ hover, 123 todo button\ focus { 124 background color rgba(0, 0, 0, 0 1); 125 } 126 127 todo button icon done { 128 color #52c41a; 129 font size 16px; 130 } 131 132 todo button icon remove { 133 color #f5222d; 134 font size 16px; 135 } コンポーネントが正しく設定されていれば、アプリを実行した後にこのようなものが表示されるはずです さあ、入力ボックスにタイトルを1つずつ入力して「 追加 追加 」ボタンを押して、いくつかのタスクを追加しましょう。すべての作成が成功した後、 createtodo createtodo 関数が readtodos readtodos 関数をトリガーし、タスクリストが自動的に更新されます。これで、次のような大きなタスクリストができているはずです タスクの横にあるチェックマークをクリックすることで、タスクを完了としてマークできます。これにより、タスクの 完了 完了 値がtrueに更新され、左側のアイコンの状態が変更されます。 残るデータ操作は削除のみで、これはタスクリストオブジェクトの最右にあるゴミ箱アイコンを押すことで行えます。オブジェクトを正常に削除した後、次のようなアラートメッセージが表示されるはずです 結論 このガイドの最後に、reactでparseの基本的なデータ操作(crud)を実行する方法を学びました。次のガイドでは、parseでサポートされているデータ型とその使用方法を示します。