Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React本机异步存储在第一次尝试时不会获取_Javascript_React Native_Asyncstorage - Fatal编程技术网

Javascript React本机异步存储在第一次尝试时不会获取

Javascript React本机异步存储在第一次尝试时不会获取,javascript,react-native,asyncstorage,Javascript,React Native,Asyncstorage,当试图显示保存到异步存储的数据时,我会出现这种行为: 相关代码: 屏幕1: class VerMais extends Component { constructor(props) { super(props); this.state = { data: '', value: [], }; } componentWillMount(){ AsyncStorage.getItem('key').then(JSON.parse

当试图显示保存到异步存储的数据时,我会出现这种行为:

相关代码:

屏幕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在装入之前立即调用。它在渲染之前调用,因此在此方法中同步设置状态不会触发重新渲染。避免在这种方法中引入任何副作用或订阅

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

我尝试在componentDidMount上提取组件,但仍然不起作用。现在,我必须手动刷新模拟器,或者双击选项卡栏重置它,然后它才会显示数据。恭喜找到解决方案。这可能有点过头了,但像Redux这样的东西也可以在这种情况下有所帮助。然后你会有一个中央数据存储,并且收藏夹屏幕可以在更新时更新。我一直在避免Redux,因为它的设置和理解似乎很复杂,但我知道有一天我必须学习它!谢谢你的帮助!