首页 > 解决方案 > 在 API 中将状态作为 id 传递本机反应

问题描述

我遇到了一个问题..首先让我告诉你完整的场景..我有一个登录页面,我从那里登录,当我登录时,我移动到主页......从登录页面我将 ID 存储在本地存储中尝试进入主页..我设置了 user_id 并传递给 API ..但是里面什么都没有,但另一方面,当我在我的视图中使用相同的状态时,它显示 user_id 这是我的代码.. .

import React, { Component } from 'react';
    import Usercard from '../usercard';
 import { View, Text,Image,StyleSheet,FlatList } from 'react-native';

 import ls from 'react-native-local-storage';
 import axios from 'axios';


  import {
    Container,

     Title,
      Content,
        Header,
         Button,
         Switch,
           Left,
           Body,
          Right,
          Icon,
          List,ListItem,Thumbnail,Footer,FooterTab
         } from "native-base";

        export default class Home extends Component {
        static navigationOptions = {
       header: null
           }
           constructor(props) {
           super(props);
         this.state = {
         name:'',
         user_id:'',
         pass:'',
         };
            }

     componentDidMount() {

       ls.get('email').then((data) => {this.setState({name:data})});
   ls.get('savedata').then((data) => {this.setState({user_id:data})});
   let passing_id=this.state.user_id
    axios.get("http://example.com/api-endpoint/"+passing_id+{


   })
  .then((response) => {
    alert(JSON.stringify(response));
    alert(this.state.user_id)


})
.catch(error => alert(error.response.data));




 }

  render() {
    return (


<Container>
    <Header>
      <Left>
      <Button transparent>
          <Icon name='camera' />
                      </Button>
      </Left>
      <Body>
        <Title style={{fontFamily: 'Bodoni 72'}}>BLAZ-10</Title>
      </Body>
      <Right>
      <Button transparent>
          <Icon name='messages' />

        </Button>
      </Right>
    </Header>


  <Content>
  <View style={{ width: '100%'}}>
  <View style={{flexDirection:'row'}}>
  <Button transparent>
      <Image source={require('../../../images/profile_1x.png')} style={{ width: 50, height: 50, }}/>
      </Button>
      <Button transparent>
      <Text>{this.state.name}{this.state.user_id}</Text>
      </Button>
      </View>

      <Image source={require('../../../images/graphimg.jpg')} resizeMode={'stretch'}style={{ width: '100%', height:150 }}/>

  </View>
  <View style={styles.comentSession}>
       <Text style={{marginLeft:5,fontWeight:'bold'}}>About Challenge</Text>
       <View style={{alignItems:'center'}}>
          <View style={{ flexDirection: 'row',justifyContent:'space-between',width:'20%'}}>
             <Icon name='favorite-border' color='#000'  />
             <Icon name='chat' color='#000'  />
             <Icon name='wechat' color='#000'  />
          </View>
       </View>
       <View style={{ flexDirection: 'row',justifyContent:'space-between',width:'100%',paddingLeft:12,paddingRight:12}} >
       <Button transparent>
           <Text style={{fontWeight:'bold'}}>Likes</Text>
        </Button>
        <Button transparent>
           <Text style={{fontWeight:'bold'}}>Comments</Text>
           </Button>
           <Button transparent>
           <Text style={{fontWeight:'bold'}}>Time</Text>
           </Button>
       </View>
    </View>
    <View style={styles.border}></View>



 <View style={{ flex: 1,height:300 }}>
     <FlatList
     style={{backgroundColor:'#dcdde1'}}
   data={[{key: 'a'}, {key: 'b'}]}
 renderItem={({item}) =>  <Usercard source={require('../../../images/avatar-1.png')} />}
   horizontal={true}
   />
   </View>
  </Content>


  <Footer>
       <FooterTab>
         <Button  >
           <Icon style={{color:'#f39c12'}} name="home" />
         </Button>
         <Button onPress={() =>this.props.navigation.navigate('Search') }>
           <Icon name="search" />
         </Button>
         <Button onPress={() =>this.props.navigation.navigate('Gallery') }>
          <Icon name="add" />
        </Button>
         <Button onPress={() =>this.props.navigation.navigate('Following') }>
           <Icon  name="heart" />
         </Button>
         <Button onPress={() =>this.props.navigation.navigate('Profile') }>
           <Icon  name="person" />
         </Button>
       </FooterTab>
     </Footer>
  </Container>





       );
    }
       }
       const styles = StyleSheet.create({
       border: {
    borderWidth:0.5,
    borderColor:'#3f3f3f',
    width:'100%',
   marginTop:0,
},
comentSession:{
  backgroundColor:'#dcdde1',
  height:100
 },


        })

问题

  1. 当我在 API 中传递我的状态时,它不能通过它,但是当我将此状态传递给像 {this.state.user_id} 这样的任何视图时,它可以工作..为什么?你们中的任何人都可以帮助我吗?

标签: react-native

解决方案


在您的承诺中,componentDidMount()您正在设置状态,这是一个回调。.then因此,在设置时间状态之前,您已经在使用状态,使用语句let passing_id=this.state.user_id;

考虑使用如下:

componentDidMount(){
  ls.get("email").then(data => {
    this.setState({ name: data });
  });
  ls.get("savedata").then(data => {
    this.setState({ user_id: data }, () => {
      let passing_id = this.state.user_id;
      axios
        .get(
          "http://172.104.217.178/blaze10/public/api/get-feed/" +
          passing_id +
          {}
        )
        .then(response => {
          alert(JSON.stringify(response));
          alert(this.state.user_id);
        })
        .catch(error => alert(error.response.data));
    });
  });
}


setState()接受第二个参数作为成功设置状态时执行的回调函数。这样就可以成功访问this.state.user_id


推荐阅读