React Native AsyncStorage不会在第一次尝试时获取

时间:2017-06-01 13:59:43

标签: javascript react-native asyncstorage

我在尝试显示保存到AsyncStorage的数据时出现此问题: http://sendvid.com/5ash8vpu

相关代码:

屏蔽1:

class VerMais extends Component {

  constructor(props) {
    super(props);
    this.state = {
      data: '',
      value: [],
    };
  }

  componentWillMount(){
    AsyncStorage.getItem('key').then(JSON.parse).then(items => {
      this.setState({value: items});
    })

    financiamentoAPI.getTextos().then((res) => {
      this.setState({
        data: res.Zona
      })
    });
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        {this.renderWarning()}
        <NavigationBar
          tintColor='#1f1f1f'
          statusBar={{style: 'light-content'}}
          title={<NavbarTitle/>}/>
        <View style={styles.container}>
          <View style={styles.botaoContainer}>
            <TouchableOpacity onPress={() => this.props.navigation.navigate('Financiamento', { data: this.state.data })} style={styles.botaoPrimeiro}>
              <Icon style={styles.icon} size={10} name={'circle'} color={'#f48529'}/><Text style={styles.texto}>  Financiamento</Text>
            </TouchableOpacity>

            <TouchableOpacity onPress={() => Communications.web('http://www.consilbuy.pt/')} style={styles.botaoPrimeiro}>
              <Icon style={styles.icon} size={10} name={'circle'} color={'#f48529'}/><Text style={styles.texto}>  Venda Já!</Text>
            </TouchableOpacity>

            <TouchableOpacity onPress={() => this.props.navigation.navigate('Favoritos', { value: this.state.value })} style={styles.botaoNoBorder}>
              <Icon style={styles.icon} size={10} name={'circle'} color={'#f48529'}/><Text style={styles.texto}>  Favoritos e Alertas</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }

屏蔽2:

const flatten = arr => arr.reduce(
  (acc, val) => acc.concat(
    Array.isArray(val) ? flatten(val) : val
  ),
  []
);

export default class Favoritos extends Component {

  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      value: this.props.navigation.state.params.value,
    };
  }

  componentWillMount(){
    this.setState({ isLoading: true});
    this.getData();
  }

  getData(){
    if(!this.state.value == 0 || !this.state.value == null){
      const promises = this.state.value.map((item, index) =>
        fetch(`URL/portalacv_ws.asmx/GetDetalhesViatura?CarID=${item}`)
         .then(response => response.json())
      )
      Promise.all(promises).then(values => this.setState({values: flatten(values), isLoading: false}))
    }
    this.setState({values: null, isLoading: false})
  }

  render() {
    const {goBack, navigate} = this.props.navigation;
    if(this.state.isLoading === true)
    {
      return(
        <View style={{ flex: 1, backgroundColor: 'white' }}>
          <NavigationBar
            tintColor='#1f1f1f'
            statusBar={{style: 'light-content'}}
            title={<NavbarTitle/>}
            leftButton={
              <NavbarLeft
                onPress={() => goBack()}
              />}
          />
          <ActivityIndicator size='small' style={{padding: 100}}/>
        </View>
      );
    }

    if(this.state.values == 0 || this.state.values == null)
    {
      return(
        <View style={{ flex: 1, backgroundColor: 'white' }}>
          <NavigationBar
            tintColor='#1f1f1f'
            statusBar={{style: 'light-content'}}
            title={<NavbarTitle/>}
            leftButton={
              <NavbarLeft
                onPress={() => goBack()}
              />}
          />
          <View style={{ flex: 1, alignItems: 'center', flexDirection:'row', justifyContent:'center'}}>
            <Text style={styles.text2}>
              Ainda não adicionou nenhuma viatura aos favoritos!
            </Text>
          </View>
        </View>
      );
    }
    return (
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        <NavigationBar
          tintColor='#1f1f1f'
          statusBar={{style: 'light-content'}}
          title={<NavbarTitle/>}
          leftButton={
            <NavbarLeft
              onPress={() => goBack()}
            />}
        />
        <View style={styles.container}>
          <FlatList
            removeClippedSubviews={false}
            data={this.state.values}
            keyExtractor={item => item.CodViatura}
            renderItem={({item}) => (
              <TouchableWithoutFeedback onPress={() => navigate('FichaFavoritos', { codigo: item.CodViatura })}>
               //DATA TO RENDER
              </TouchableWithoutFeedback>
            )}
          />
        </View>
      </View>
    );
  }
}

Screen1是我点击“Favoritos e Alertas”的屏幕,屏幕2是第二次尝试只显示汽车的屏幕。 我有没有人知道为什么我第一次打开屏幕时没有显示汽车?

2 个答案:

答案 0 :(得分:1)

来自componentWillMount

的文档
  

在安装发生之前立即调用componentWillMount()。它在render()之前调用,因此在此方法中同步设置状态不会触发重新呈现。避免在此方法中引入任何副作用或订阅。

https://facebook.github.io/react/docs/react-component.html#componentwillmount

也许同步处理setState所以它不会触发重新渲染?

执行数据提取的推荐位置在componentDidMount

答案 1 :(得分:0)

我发现我做错了什么。当我的组件挂载时,我正在获取本地数据,因此不会显示将新车添加到收藏夹,因为组件已经安装,因此无法再次获取数据。

当我点击按钮打开收藏夹屏幕时,我不得不进行提取,然后才导航到屏幕。像这样:

  fetchAsync(){
    AsyncStorage.getItem('key').then(JSON.parse).then(items => {
      this.setState({value: items});
      this.props.navigation.navigate('Favoritos', { value: this.state.value })
    })
  }

并在按钮上设置onPres:

onPress={() => this.fetchAsync()}