gpt4 book ai didi

reactjs - React Native 导航/上下文 API

转载 作者:行者123 更新时间:2023-12-03 13:31:50 25 4
gpt4 key购买 nike

我正在使用 React-Native-Navigation 和 Context api。

我用下面的 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 中,该数组工作正常,但是当我转到 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));

关于reactjs - React Native 导航/上下文 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51896173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com