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

React Native AsyncStorage won't fetch on first try

我在尝试显示保存到 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>
    );
  }
}

屏幕 1 是我点击 "Favoritos e Alertas" 的屏幕,屏幕 2 是第二次尝试时仅显示汽车的屏幕。 有谁知道为什么我第一次打开屏幕时没有显示汽车?

来自 componentWillMount

的文档

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.

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

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

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

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

当我单击按钮打开收藏夹屏幕然后导航到该屏幕时,我必须进行提取。像这样:

  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()}