我在没有react-navigation
的情况下使用redux
。所以我有两个标签,每个标签都有自己的堆栈导航器,每个标签都有一个屏幕。所以我需要和两个屏幕中的locations
阵列。目前我在两个屏幕上都这样做:
state = { locations: [] };
componentDidMount() {
this.getAllLocations();
}
async getAllLocations() {
let locations = await this.getMoviesFromApi();
this.setState({ locations });
}
我只想将这个数组放在一个位置,两个组件都应该共享这个单一的事实来源。因此,任一屏幕所做的更改都会反映在另一个屏幕上。没有redux,这可能吗?
RN 0.59在发布后已经开启了很大的可能性。其中一个是反应钩,可以在最新版本中使用......将来反应钩将随处使用。相信我。所以,不久前我寻找使用反应钩子的全局状态的可能性,并找到了reactn库。它使用react native钩子,甚至可以在CLASS组件中使用全局状态。这为主题和共享数据打开了一扇新的大门。现在,我的应用程序仅使用此库支持亮/暗模式,动态字体大小,语言和早期实现“门户”。
关于它的最好的部分是你可以像状态一样使用它。不需要提供者或redux东西(尽管它提供了它)。它可以与反应导航集成(它需要修改一些源代码,最多添加“n”进行反应,并引用全局变量)。太棒了,我喜欢它。
我一直在考虑在媒体上做一篇关于这个的文章,因为lib在RN社区中不那么流行,但是希望你能给它一个机会,它只有22KB,不到一个完整的组件。
作为替代方案,您可以考虑使用钩子编写自己的库。但这会很难。试试吧,没有回头路
如果你有一个单例对象是可能的:
export default class SharedData {
constructor(){
if(SharedData.instance){
return SharedData.instance;
}
this.state = {locations:[]};
this.listners =[];
SharedData.instance = this;
return SharedData.instance;
}
setLocations(locations){
this.state.locations = locations;
this.listners.forEach(listner=>listner(this.state.location));
}
getLocations(){
return this.state.locations;
}
addListner(listner){
this.listners.push(listner);
return listner;
}
removeListner(listner){
let index = this.listners.indexOf(listner);
if(index > -1){
this.listners.splice(index,1);
}
}
}
然后在您要访问共享位置的每个选项卡中:
// get an instance of SharedData
this.sharedData = new SharedData();
// subscribe to locations changes
this.listner = sharedData.addListner((locations)=>{
this.setState({locations});
});
// set locations
this.sharedData.setLocations([]);
// unregister when destroying the component
this.sharedData.removeListner(this.listner);
我想为了实现你的目标,你需要一种存储“全局数据”的机制,如果你不喜欢Redux,因为它需要大量的设置才能实现共享全局数据这个简单的任务,然后你会问你unstated ...这很简单