اذهب إلى المحتوى
  • 0

التعديل الصحيح لمصفوفات ال state في React.js

Rayden Storm

السؤال

أريد إضافة عنصر إلى نهاية مصفوفة ال state ، هل هذه هي الطريقة الصحيحة للقيام بذلك؟

this.state.array.push(newelement);
this.setState({ array:this.state.array });

أنا قلق من أن تعديل المصفوفة في مكانها بالدفع قد يسبب مشكلة 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

مرحباً بك: 
لا يمكنك استخدام ال push عند التعديل على مصفوفة لأنها تقوم بعمل mutation وقد حذر فريق React من استعمالها ولكن عوضاً عن ذلك يمكنك استخدام concat

this.setState({ array: this.state.array.concat('new Item') });

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

لا يجوز التعديل على this.state بشكل مباشر وإنما فقط من خلال setState، يمكن تحقيق ما تريد بعدة طرق.

اﻷولى باستخدام concat:

this.setState({ array: this.state.array.concat('new Item') });

الثانية باستخدام rest array:

this.setState({ array: [...this.state.array,'new Item'] });

الثالثة نسخ المصفوفة قبل تعديلها هكذا:

// make a copy, newArray !== this.state.array
const newArray = [...this.state.array]
newArray.push('new Item');
this.setState({ array: newArray });

شخصياً في حالتك أفضل rest array لكن الطريقة الثالثة قد تكون ضرورية في حال كان التعديل على المصفوفة أعقد من مجرد إضافة عنصر إليها.

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

السلام عليكم 

لا يا صديقي في react يفضل انت تستخدم concat بدلا كم push 

ولا يجوز ان تعدل على اي state الا من خلال setState 

وهذا اقتباس من شخص عنده نفس المشكلة على stackoverflow

اقتباس

When you use push, you are setting selectedNumbers to be the return value of the push operation, which is the length of the new array according to the mozilla developer docs. Push also attempts to mutate the array in state, which as PhilippSpo said doesn't work.

Either use concat as you were before or copy the selectedNumbers to a new array, push your value into that one, and then set selectedNumbers to the new array. If you're using ES6 you can use the spread operator as other users have pointed out

بالتوفيق

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...