当前位置 : 主页 > 网页制作 > React >

reactjs – React Native Navigation / Context API

来源:互联网 收集:自由互联 发布时间:2021-06-15
我正在使用带有Context api的React-Native-Navigation. 我正在用下面的HOC组件包裹我的屏幕. const ProviderWrap = Comp = props = ( Provider Comp {...props} / /Provider );Navigation.registerComponent('app.AuthScreen', () = P
我正在使用带有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));
网友评论