具有AsyncStorage的动态构建组件

时间:2019-08-31 15:39:59

标签: react-native

我正在尝试在_buildComponent函数中构建子组件,并将结果放入render()中,只需看下面的代码即可

我遇到的问题是AsyncStorage.getItem()正在运行异步,从而导致它在render()方法中不呈现任何内容

...反应

 _buildComponent = async (key) => {
          let val = await AsyncStorage.getItem(key)
            console.log(key + ' : ' +val);
            debugger;//code will run to here after ScrollableTabView finish rendering. but I need to build Arr first.
          if(val == 1) return <PopularView tabLabel={key}>{key}</PopularView>
      }


render() {
            let Arr = Constants.TABS.map(item =
                return this._buildComponent(item).done();
          })

          debugger;//code will run into here directly without waiting building Arr above, making Arr was null when rendering ScrollableTabView

        return (
            <ScrollableTabView
                tabBarBackgroundColor='#2196F3'
                tabBarInactiveTextColor='mintcream'
                tabBarTextStyle={{marginTop:27}}
            initialPage={0}
            renderTabBar={() => <ScrollableTabBar/>}
            >

            {Arr}// Arr is null here because the _buildComponent method was not finish yet.
            {/* <PopularView tabLabel='Java'>Java</PopularView>
            <PopularView tabLabel='IOS'>IOS</PopularView>
            <PopularView tabLabel='Android'>Android</PopularView>
            <PopularView tabLabel='Javascript'>Javascript</PopularView> */}
          </ScrollableTabView>
        )
    }

...

我已在评论中解释了我的问题,谢谢,谢谢。我不知道在运行render()之前准备变量的最佳实践是什么。

1 个答案:

答案 0 :(得分:0)

尝试此解决方案,该解决方案可动态添加标签页(已更新)

_buildComponent = async () => {

    let tabsData = [];

    await AsyncStorage.multiGet(Constants.TABS).then(response => {

            Constants.TABS.forEach((item,index) => 
                {
                    if(response[index][1] == 1) {
                        tabsData.push(response[index][0]); // key
                    }
                }
            );

            // This only render once
            this.setState({ tabLabels: tabsData })
        })
}

componentDidMount() {
   this._buildComponent()
}

render() {
    const tabLabelList = this.state.tabLabels.map((key) => {
        return (
          <PopularView tabLabel={key}>{key}</PopularView>
        )
    })

    return (
        <ScrollableTabView
            tabBarBackgroundColor='#2196F3'
            tabBarInactiveTextColor='mintcream'
            tabBarTextStyle={{marginTop:27}}
        initialPage={0}
        renderTabBar={() => <ScrollableTabBar/>}
        >

        {tabLabelList}

      </ScrollableTabView>
    )
}