mobX - Filter countries in react native?

流过昼夜 提交于 2019-12-05 18:22:35

I saw a few possible problems, so I slightly changed the approach.

Working example

UPDATED Working example. Note this is untested in react-native, but it should work.

The code

@observer
class Country extends React.Component {


    @observable filterTermValue = '';
    @observable countriesList = [
      {'slug': 'amsterdam', 'name': 'Amsterdam'},
      {'slug': 'usa', 'name': 'United States'},
      {'slug': 'vienna', 'name': 'Vienna'}
    ];

    @computed get filtered() {
      let filteredList = this.countriesList.filter(
        t=>t.name.toLowerCase().indexOf(this.filterTermValue)>-1
      );
      if (filteredList.length)
        return filteredList;
      return this.countriesList;
    }

    render() {
        return (
          <div>
              Term: <input placeholder="Start typing country"
                 onKeyUp={this.onChangeFilterTerm} />

              {this.filtered.map(country =>
                  <div key={country.slug}>
                    <p>{country.name}</p>
                  </div>
              )}
          </div>
        )
    }

    @action onChangeFilterTerm = value => {
        this.filterTermValue = value.toLowerCase();
    }
}

React-native gotchyas

Use onChangeText correct signature

jsx:

    <input placeholder="Start typing country"
            onKeyUp={this.onChangeFilterTerm} />

js:

    @action onChangeFilterTerm = value => {
        this.filterTermValue = value.toLowerCase();
    }

Use mobx-react/native

If its still not working, I would double check this:

Dont:

import {observer} from 'mobx-react';

Do:

import {observer} from 'mobx-react/native';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!