0

尝试显示保存到 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 是仅在第二次尝试时显示汽车的屏幕。有谁知道为什么我第一次打开屏幕时没有显示汽车?

4

2 回答 2

1

从文档中componentWillMount

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

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

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

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

于 2017-06-01T23:29:52.623 回答
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()}
于 2017-06-02T10:16:52.310 回答