GVKun编程网logo

实现CollectionChanged(实现中华民族伟大复兴)

2

在本文中,我们将带你了解实现CollectionChanged在这篇文章中,我们将为您详细介绍实现CollectionChanged的方方面面,并解答实现中华民族伟大复兴常见的疑惑,同时我们还将给您一

在本文中,我们将带你了解实现CollectionChanged在这篇文章中,我们将为您详细介绍实现CollectionChanged的方方面面,并解答实现中华民族伟大复兴常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的(React) useDispatch TypeError: Object(...) is not a function handleChange、angular – Alias已被“–collection”选项使用,不能被“–change-detection”选项使用、angular – FormControl.detectchanges – 为什么要使用distinctUntilChanged?、c# – INotifyPropertyChanged和ObservableCollection WPF

本文目录一览:

实现CollectionChanged(实现中华民族伟大复兴)

实现CollectionChanged(实现中华民族伟大复兴)

我已添加CollectionChangedeventhandler(onCollectionChanged)到其中一个ObservableCollection属性。

我发现该onCollectionChanged方法仅在添加项目或将项目移除到集合中时才被调用,而在集合项被编辑时不被调用。

我想知道如何在单个集合中发送新添加,删除和编辑的项目的列表/集合。

谢谢。

答案1

小编典典

您必须为PropertyChanged每个项目(必须实现INotifyPropertyChanged)添加一个侦听器,以获取有关在可观察列表中编辑对象的通知。

public ObservableCollection<Item> Names { get; set; }public List<Item> ModifiedItems { get; set; }public ViewModel(){   this.ModifiedItems = new List<Item>();   this.Names = new ObservableCollection<Item>();   this.Names.CollectionChanged += this.OnCollectionChanged;}void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e){    if (e.NewItems != null)    {        foreach(Item newItem in e.NewItems)        {            ModifiedItems.Add(newItem);            //Add listener for each item on PropertyChanged event            newItem.PropertyChanged += this.OnItemPropertyChanged;                 }    }    if (e.OldItems != null)    {        foreach(Item oldItem in e.OldItems)        {            ModifiedItems.Add(oldItem);            oldItem.PropertyChanged -= this.OnItemPropertyChanged;        }    }}void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e){    Item item = sender as Item;    if(item != null)       ModifiedItems.Add(item);}

也许您必须检查ModifedItems-List中是否已经存在某些项目(使用List的方法Contains(object
obj)),并且仅在该方法的结果为 false时 添加一个新项目。

该类Item必须实现INotifyPropertyChanged。查看此示例以了解操作方法。正如罗伯特·罗斯尼(Robert
Rossney)所说,IEditableObject如果您有此要求,您也可以使用。

(React) useDispatch TypeError: Object(...) is not a function handleChange

(React) useDispatch TypeError: Object(...) is not a function handleChange

如何解决(React) useDispatch TypeError: Object(...) is not a function handleChange?

我正在做一个简单的 React 应用程序,其中任何用户在输入文本中引入一个文本,它会自动更新商店中的状态。 这是 React 的非常简单的实践,但我对这个错误感到非常挣扎和沮丧,因为我尝试了所有方法,但仍然遇到同样的问题。

我正在使用“react-redux”和“@reduxjs/toolkit”依赖项。我尝试了所有方法,检查并比较了类似问题的类似示例和解决方案,我从头开始重新制作了该应用程序,以确保不同版本的依赖项没有任何问题,并且我尝试使我的代码非常简单它有效,但无效。

我希望你们中的任何人都可以给我建议或解决方案。 谢谢!!

错误

TypeError: Object(...) is not a function
handleChange
C:/Users/Ruben/Desktop/Projects/React/reddit2/reddit/src/features/search/SearchBar.js:14
  11 | 
  12 | 
  13 |  const handleChange = (e) => {
> 14 |    dispatch(setSearchTerm(e.target.value))
     | ^  15 |  }
  16 | 
  17 | 
View compiled
▶ 19 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.  Click the ''X'' or hit ESC to dismiss this message.

这些是文件:

SearchBar 组件

import React from "react";
import {usedispatch,useSelector} from "react-redux";
import {setSearchTerm,selectSearchTerm} from "../search/searchSlice";


export const SearchBar = () => {
  
  
  const dispatch = usedispatch();
  const term = useSelector(selectSearchTerm);


  const handleChange = (e) => {
    dispatch(setSearchTerm(e.target.value))
  }


  return(
    <div>
      <input
        id="search"
        type="text"
        value={term}
        onChange={handleChange}
        placeholder="Introduce your Topic"
        />
    </div>
  );
};

searchSlice

import {createSlice} from "@reduxjs/toolkit";


export const searchSlice = createSlice({
  name: ''search'',initialState: '''',reducer: {
    setSearchTerm: (state,action) => {state.search = action.payload},}
});

export const {setSearchTerm} = searchSlice.actions;

export const selectSearchTerm = (state) => state.search;

export default searchSlice.reducer;

商店

import {configureStore} from "@reduxjs/toolkit";
import searchReducer from "../features/search/searchSlice";

export default configureStore({
  reducer: {
    search: searchReducer,},});

索引

import React from ''react'';
import ReactDOM from ''react-dom'';
import { Provider } from "react-redux";
import ''./index.css'';
import App from ''../src/App/App'';
import reportWebVitals from ''./reportWebVitals'';
import store from "../src/App/store";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>  
  </React.StrictMode>,document.getElementById(''root'')
);

Package.json

{
  "name": "reddit","version": "0.1.0","private": true,"dependencies": {
    "@reduxjs/toolkit": "^1.5.1","@testing-library/jest-dom": "^5.13.0","@testing-library/react": "^11.2.7","@testing-library/user-event": "^12.8.3","react": "^17.0.2","react-dom": "^17.0.2","react-redux": "^7.2.4","react-scripts": "4.0.3","web-vitals": "^1.1.2"
  },

解决方法

问题

  1. 您在 createSlice 中有一个拼写错误,正确的键是 reducers,带有“s”,而不是 reducer。这导致切片操作实际上未定义。
  2. 您的状态不太正确。它不是一个可起草的对象。

解决方案

更正reducer key并提供正确的状态。

export const searchSlice = createSlice({
  name: "search",initialState: { search: "" },// <-- object state
  reducers: {
    setSearchTerm: (state,action) => {
      state.search = action.payload; // <-- update property
    }
  }
});

export const { setSearchTerm } = searchSlice.actions;

export const selectSearchTerm = (state) => state.search.search; // <-- select property

export default searchSlice.reducer;

Edit react-usedispatch-typeerror-object-is-not-a-function-handlechange

angular – Alias已被“–collection”选项使用,不能被“–change-detection”选项使用

angular – Alias已被“–collection”选项使用,不能被“–change-detection”选项使用

环境:

> Ubuntu 16.04
> Angular CLI 1.7.3

我通过执行生成组件仪表板来获取错误,但是也会发生ng generate c

$ng generate component dashboard
The "c" alias is already in use by the "--collection" option 
and cannot be used by the "--change-detection" option.
Please use a different alias.

我试图在npm中查找错误,蚂蚁我得到以下错误

$npm list
...
npm ERR! peer dep missing: @angular-devkit/core@0.4.5,required by @schematics/angular@0.4.5
npm ERR! peer dep missing: @angular-devkit/schematics@0.4.5,required by @schematics/angular@0.4.5

它看起来与npm validate别名有关

function angular-cli.command.prototype.validateAlias (option,alias)

但我不确定为什么选择“c”代替“组件”.

解决方法

我不知道这个错误的根本原因,但是这个 commit改变了很多别名(包括“c”代表“组件”)……
如果在node_modules/@schematics/angular/component/schema.json中将其本地更改为“cd”,则ng generate再次起作用.

请注意,在新项目中使用ng g组件测试时,我不会重现此错误.我在产生错误的项目中使用@nrwl / nx.问题可能在于版本不匹配……我不知道是什么.

angular – FormControl.detectchanges – 为什么要使用distinctUntilChanged?

angular – FormControl.detectchanges – 为什么要使用distinctUntilChanged?

阅读 How to use RxJs distinctUntilChanged?和 this,似乎distinctUntilChanged改变输出流只提供不同的连续值.

我认为这意味着如果相同的值立即连续到达,您实际上是过滤流并且只获得该重复值的一次出现.

所以,如果我这样写:

this.myFormControl.valueChanges
  .debounceTime(1000)
  .distinctUntilChanged()
  .subscribe(newValue => {
    console.log('debounced: ',newValue);
  });

我看到输出没有区别:

this.myFormControl.valueChanges
  .debounceTime(1000)
  .subscribe(newValue => {
    console.log('debounced: ',newValue);
  });

我已经看到一些地方建议在表单输入上订阅valueChanges时使用distinctUntilChanged – 但实际上并没有得到原因.

这是一个输入,所以如果用户输入它总是在变化,对吗?这些值将始终是不同的,因此您只需添加一个额外的操作来无缘无故地过滤输入.

或者我在这里遗漏了什么?

编辑

根据我的第一个代码示例使用distinctUntilChanged,我创建了一个带有特朗普先生值的表单输入,并确保它保存在模型中.

然后我点击控件内部并粘贴了特朗普先生.由于值是相同的,我原本预计不会看到任何记录 – 控件具有与之前相同的值,所以distinctUntilChanged肯定应该忽略它?

编辑2

进一步查看我的测试后,这种行为似乎是因为我使用了一个AbstractControls数组:

this.itemsControl = <FormArray>this.form.controls['items']; 
...
this.itemsControl.controls[index].valueChanges...

所以虽然有点奇怪,当输入的值相同时它仍然会触发,我猜我需要连接到这个数组项(表单组)中的实际输入的valueChanges,而不是数组项本身.

编辑3

因此,在将EDIT 2中的代码更改为以下内容后,将已存在的相同值粘贴到输入控件中不会触发valueChanges(如预期的那样).在EDIT 2中,valueChanges挂钩到整个formGroup,而不是单个输入控件(在本例中称为content):

let fg = this.itemsControl.controls[index]; // get the formGroup
fg['controls'].content.valueChanges
  .debounceTime(1000)
  .distinctUntilChanged()
  .subscribe(newValue => {...});

解决方法

使用debounceTime(1000)意味着我们只在用户停止输入1秒时发送请求,在此期间用户可以写入3个字符然后擦除它们,因此输入值自上次请求后没有改变但是你发送的是请求,以避免您可以使用.distinctUntilChanged()

this.myFormControl.valueChanges
      .debounceTime(1000)
      .distinctUntilChanged()
      .subscribe(newValue => {
        console.log('debounced: ',newValue)
      });

c# – INotifyPropertyChanged和ObservableCollection WPF

c# – INotifyPropertyChanged和ObservableCollection WPF

现在我有一个只显示一个月的日历(我通过的月份).我试图让用户从comboBox中选择月份和年份并更新日历.我使用observablecollection绑定,我很熟悉.我不知道INotifyPropertyChanged如何工作.我以前从未使用过它.非常感谢任何帮助或建议.这是我到目前为止:

public class Schedule : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void Update(int propertyName)
    {
        if (propertyName != null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                 handler.Invoke(this,new PropertyChangedEventArgs(propertyName.ToString()));
        }
    }


   // public void UpdateCal(PropertyChangedEventArgs e)
   // {
    //    if (PropertyChanged != null)
    //        PropertyChanged(this,e);
  //  } 
    public string MonthWeek { get; set; }
    public string Year { get; set; }
    public string Month { get; set; }
    public string day { get; set; }
    public string WeekOfYear { get; set; }
    public string dayofweek { get; set; }

   // public string month {
    //    get {return Month; }
    //    set
    //    {
     //       UpdateCal(new PropertyChangedEventArgs("month"));
      //  }
   // }
    public int WeekNo { get; set; }
    public int WeekDay { get; set; }
    public DateTime Date { get; set; }
 }

—这是另一个类,它确定了每个日期在网格上的位置—-

public SchedulePage(MainWindow parentForm)
    {
        InitializeComponent();

        pick = Convert.ToInt32(comboMonth.SelectedItem) + 1;
        _parentForm = parentForm;
        // DateTime date = new DateTime(year,month,day);
        var t = new List<Schedule>();
        DateTime curr = DateTime.Now;
      //  comboMonth.Items.Add(curr.Month);
        DateTime newcurr = new DateTime(2011,pick,1);
     //   pickdate = datePickercal.SelectedDate;
      //  DateTime newcurr = new DateTime(curr.Year,curr.Month,1);
        var cal = System.Globalization.DateTimeFormatInfo.CurrentInfo.Calendar;
        var ms = cal.GetWeekOfYear(new DateTime(newcurr.Year,newcurr.Month,1),System.Globalization.CalendarWeekRule.FirstDay,System.DayOfWeek.Sunday);
        for (var i = 1; newcurr.Month == pick; newcurr = newcurr.AddDays(1))
        {
            var sched = new Schedule();
            var month_week = (newcurr.Day / 7) ;
            sched.MonthWeek = newcurr.GetWeekOfMonth().ToString();
            sched.Month = newcurr.Month.ToString();
            sched.Year = newcurr.Year.ToString();
            sched.day = newcurr.Day.ToString();
            sched.WeekOfYear = cal.GetWeekOfYear(newcurr,DayOfWeek.Sunday).ToString();
            sched.dayofweek = newcurr.DayOfWeek.ToString();
            t.Add(sched);

                _parentForm.bindings.schedule.Add(new Schedule { WeekNo = newcurr.GetWeekOfMonth()-1,WeekDay = (int)newcurr.DayOfWeek,day = newcurr.Day.ToString() });

        }
        lblDate.Content = (newcurr.Month -1) + "/" + newcurr.Year;

         DataContext = _parentForm.Bindings;

—这个类使观察收集—–

public partial class BindingCamper 
{  // This class assist in binding campers from listview to the textBoxes on the camperspage
    public ObservableCollection<Camper> Campers { get; set; }
    public ObservableCollection<Staff> StaffMembers { get; set; }
    public ObservableCollection<Schedule> schedule { get; set; }
    public BindingCamper()
    {
        Campers = new ObservableCollection<Camper>();
      StaffMembers = new ObservableCollection<Staff>();
      schedule = new ObservableCollection<Schedule>();
    }

解决方法

这是您通常实现INotifyPropertyChanged的方式:

public class Schedule : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this,new PropertyChangedEventArgs(propertyName));
    }

    private string _monthWeek;
    public string MonthWeek
    {
        get { return _monthWeek; }
        set
        {
            if (value != _monthWeek)
            {
                _monthWeek = value;
                OnPropertyChanged("MonthWeek");
            }
        }
    }

    // And so on for other properties...

}

基本上,每次更新属性时都需要触发PropertyChanged事件,因此每个setter都必须调用OnPropertyChanged.请注意,您无法使用自动实现的属性执行此操作,因为您需要在setter中添加自定义逻辑.

今天关于实现CollectionChanged实现中华民族伟大复兴的介绍到此结束,谢谢您的阅读,有关(React) useDispatch TypeError: Object(...) is not a function handleChange、angular – Alias已被“–collection”选项使用,不能被“–change-detection”选项使用、angular – FormControl.detectchanges – 为什么要使用distinctUntilChanged?、c# – INotifyPropertyChanged和ObservableCollection WPF等更多相关知识的信息可以在本站进行查询。

本文标签: