【问题标题】:Passing data in JSON Object from one class to second将 JSON 对象中的数据从一类传递到另一类
【发布时间】:2020-08-04 08:33:54
【问题描述】:

你好 StackOverflow 我想将我的 JSON 对象中的数据传递到我的抽屉类中。我无法在第二堂课中访问此对象

下面的代码我的类我的 userLoginFunction 它将给我下面给出的我的 json 对象屏幕截图

UserLoginFunction = () =>{
 const { UserContact }  = this.state ;
 const { UserPassword }  = this.state ;
 if(this.state.UserContact == ""){
   ToastAndroid.show('Pleas Enter Contact Number Correctly ',ToastAndroid.SHORT)
 }
 else if (this.state.UserPassword == ""){
   ToastAndroid.show('Please Enter Password Correctly',ToastAndroid.SHORT)
 }
 else{

fetch(urls.localhosturl + urls.login, { 
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
 
    user_contact: UserContact,
    user_password: UserPassword,
   
 
  })
 
})
      
      .then((response) => response.json())
      .then((responseJson) => {

        
        // If server response message same as Data Matched
         if(responseJson.status === '200')
          {
            //Save User Details to Local Storage
            AsyncStorage.setItem("responseJson", JSON.stringify(responseJson));            this.props.navigation.navigate("Home","DrawerComponent",{userData:responseJson.data,
            });
            console.log(responseJson.data)
        }
        else{
          ToastAndroid.show(responseJson,ToastAndroid.SHORT);
          //Alert.alert(string,responseJson);
          
        }

      }).catch((error) => {
        console.error(error);
      });
 
    }
  }

这是我的drawercomponent 类,我想在其中访问该 json 对象数据,如用户名等...

class DrawerComponent extends React.Component {  
  drawerOptions = [
    {title: 'About Us', route: 'AboutUs', icon: 'md-card'},
    {title: 'Journey Prayers', route: 'Prayers', icon: 'md-ribbon'},
    {title: 'Recharge', route: 'Recharge', icon: 'md-cash'},
    {title: 'Help Line', route: 'HelpLine', icon: 'md-call'},
    {title: 'Media', route: 'Media', icon: 'md-radio'},
    {title: 'Motorway Sites', route: 'MotorwaySites', icon: 'md-pin'},
    {title: 'Notifications', route: 'Notifications', icon: 'md-notifications'},
    
  ];

  render() {
    
    return (
      <SafeAreaView style = {{flex : 1}}>
        <ScrollView>
      <View style = {{height : 150 , backgroundColor : 'white' , alignItems : 'center' , justifyContent : 'center'}}>
            <Image source = {require('../images/profile.jpg') } style = {{height : 120 , width : 120 ,
          borderRadius : 60 , marginTop : 45}} />
          //here i want to display username from json object
          <Text>Haseeb</Text>
          
       </View>
      <View style = {{ marginTop : 30,height : 30 , backgroundColor : 'white' , alignItems : 'center' , justifyContent : 'center'}}>
          <Text style= {{fontWeight: 'bold',fontSize: 20,textAlign: 'center'}}>
          </Text>
      </View>
      <View style={{borderBottomColor: '#dedede',marginTop: 25, borderBottomWidth: 1}}/>


      <View style={{flex: 1, marginTop: 10}}>
        {this.drawerOptions.map(item => (


          <TouchableOpacity
            style={{padding: 16}}
            onPress={() => {
              this.props.navigation.toggleDrawer();
              this.props.navigation.navigate(item.route);
            }}
            key={item.title}>
            <Text >
            <Ionicons name = {item.icon} size={24} style={{color: '#282828'}} />
            <Text>  </Text>
              {item.title}</Text>
          </TouchableOpacity>
        ))}
      </View>
      </ScrollView>
      </SafeAreaView>
    );
  }
}

【问题讨论】:

  • 旁注:JSON 是一种用于数据交换的文本表示法(More here.) 如果您正在处理 JavaScript 源代码,而不是处理 string,那么您就不是在处理 JSON。您有一个对象(调用 .json() 的结果),而不是 JSON 对象。
  • 请将问题中的代码缩减为 minimal reproducible example 来演示问题,最好是使用 Stack Snippets([&lt;&gt;] 工具栏按钮)的可运行代码。 Stack Snippets 支持 React,包括 JSX; here's how to do one.

标签: javascript json react-native


【解决方案1】:

嗯,你走的很好。您已经将项目保存到本地存储中,因此在第二个组件中,您只需在组件安装时加载它。为此,您将使用AsyncStoragegetItem 方法并将结果保存在您的状态中:

class DrawerComponent extends React.Component {
  state = { myItem: { data: { user_name: "" } } }

  componentDidMount() {
    const stringifiedItem = AsyncStorage.getItem("responseJson");
    if (stringifiedItem) {
      // Turn the string back into an object
      const myItem = JSON.parse(stringifiedItem);
      // Put it into state
      this.setState({ myItem });
    }
  }
}

【讨论】:

  • 取决于它最初是如何保存在 responseJson 对象中的。查看您的屏幕截图,应该可以通过this.state.myItem.data.user_name 访问它。
  • 当我想在 this.state.myItem.data.user_name 中显示它时,它给我错误“TypeError:undefined is not an object (evaluate 'this.state. myItem.data.user_name') "
【解决方案2】:

如果你保存了整个对象,这就是如何在课堂的任何地方获取异步存储数据。

state = { userData: {}}

  async componentDidMount() {
    const stringifiedItem = await AsyncStorage.getItem("responseJson");
    // Turn the string back into an object
    const userData = JSON.parse(stringifiedItem);
    // Put it into state
    this.setState({ userData:userData.data });
    //console.log(userData.data)
    
  }
  
  

这是从异步存储中获取数据到文本组件的方法

&lt;Text&gt;{this.state.userData.user_name}&lt;/Text&gt;

【讨论】:

    猜你喜欢
    • 2016-09-06
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    相关资源
    最近更新 更多