加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – React Native Navigation / Context API

发布时间:2020-12-15 16:15:33 所属栏目:百科 来源:网络整理
导读:我正在使用带有Context api的React-Native-Navigation. 我正在用下面的HOC组件包裹我的屏幕. const ProviderWrap = Comp = props = ( Provider Comp {...props} / /Provider );Navigation.registerComponent('app.AuthScreen',() = ProviderWrap(AuthScreen)
我正在使用带有Context api的React-Native-Navigation.

我正在用下面的HOC组件包裹我的屏幕.

const ProviderWrap = Comp => props => (
    <Provider>
      <Comp {...props} />
    </Provider>
  );

Navigation.registerComponent('app.AuthScreen',() => ProviderWrap(AuthScreen));
Navigation.registerComponent('app.FindPlaceScreen',() => ProviderWrap(FindPlaceScreen));
Navigation.registerComponent('app.SharePlaceScreen',() => ProviderWrap(SharePlaceScreen));

这是我的提供者组件

class Provider extends Component {
  state = {
    placeName: 'hello',image: 'https://images.unsplash.com/photo-1534075786808-9b819c51f0b7?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=4dec0c0b139fb398b714a5c8264b4a9a&auto=format&fit=crop&w=934&q=80',places: [],}

  textInputHandler = (text) => {
    this.setState({
      placeName: text,})
  }

  searchInputHandler = (text) => {
    const SearchedPlace = this.state.places.filter(place => {
      return place.name.includes(text)
    })
    this.setState(prevState => {
      return {
        places: SearchedPlace,}
    })
  }

  placeSubmitHandler = () => {
    if (this.state.placeName) {
      this.setState(prevState => {
        return {
          places: [...prevState.places,{
            name: prevState.placeName,image: prevState.image,}],placeName: '',}
      })
    } else {
      return;
    }
  }

  placeDeleteHandler = (id,deleteModal) => {
    const newPlaces = this.state.places.filter((place,index) => {
      return index !== id
    })
    this.setState({
      places: newPlaces,})
    deleteModal();
  }

  render() {
    return (
      <GlobalContext.Provider value={{
        state: this.state,textInputHandler: this.textInputHandler,placeSubmitHandler: this.placeSubmitHandler,placeDeleteHandler: this.placeDeleteHandler,searchInputHandler: this.searchInputHandler,}}>
        {this.props.children}
      </GlobalContext.Provider>
    )
  }
}

我的问题是上下文状态不在屏幕之间共享.在我的上下文状态中我有一个我在SharePlaceScreen中添加的places数组工作正常但是当我转到FindPlaceScreen时,上下文状态的地方是空的.好像我每个屏幕都有两个独立的上下文.

解决方法

这是一个单例对象的例子,你有许多实现你使用es6类也… es6 examples

var SingletonState = (function () {
    var state;

    function createState() {
        return {someKey:'what ever'};
    }

    return {
        getState: function () {
            if (!state) {
                 state = createState();
            }
            return state;
        }
    };
})();

// usage 
var state1 = SingletonState.getState();
var state2 = SingletonState.getState();

console.log("Same state? " + (state1 === state2));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读