【问题标题】:Showing value from array of data in React Native在 React Native 中显示数据数组中的值
【发布时间】:2020-01-30 01:43:00
【问题描述】:

我从我的 API 中获取了这些数据。如何在文本输入中显示 name 属性的值?

[
    {
        "id": "1",
        "userid": "",
        "is_admin": "1",
        "name": "Anshul Gupta",
        "email": "testuser@gmail.com",
        "company": "Kissui Metaliks and Steels Pvt. Ltd.",
        "jobtitle": "Director",
        "address": "366 and 368, MIE Part A, Bahadurgarh,Haryana,IndiaBahadurgarh, Haryana",
        "cityid": "haryana",
        "stateid": "Abohar",
        ...
    }
]

【问题讨论】:

  • 你到底是什么意思? yourArray[0]['name'] 返回名称!
  • 从 api 获取此数据希望在 textinput 上呈现其值,如姓名、电子邮件等
  • 请分享输入的区号!
  • 构造函数(props) { super(props); this.state = { dataSource:[], } } async componentDidMount(){ try { AsyncStorage.getItem("user").then(async (user)=>{ const response = await fetch('myAPi=' + userData .id ); const responseJson = await response.json(); this.setState({ dataSource: responseJson, }) }) } }

标签: arrays reactjs react-native fetch


【解决方案1】:

嗨@DivyaLal 它是一个简单直接的答案。您需要做的就是将特定数组的索引与您需要显示的任何键一起使用。正如您所说,您需要在 textinput 中显示值,请查看以下示例

    import React, { Component } from 'react';
    import { TextInput, View } from 'react-native';

    export default class HelloWorldApp extends Component {

      constructor(props) {
        super(props);
        this.state = {
arr= yourArr
}
      }


     render() {
        return (
          <View>
            <TextInput 
    value = {arr[0].name}/> // to display name in textinput

<TextInput 
value={arr[0].email}/> // to dsiplay email
          </View>
        );
      }
    }

希望这会有所帮助....快乐编码!

【讨论】:

    【解决方案2】:

    我不确定,但我想这就是你要找的:

            import React, { Component } from 'react';
            import { Text, View, TextInput } from 'react-native';
    
            export default class HelloWorldApp extends Component {
    
              constructor(props) {
                super(props);
                this.state = { dataSource:[]}
              }
    
              async componentDidMount(){
                try {
                  AsyncStorage.getItem("user")
                    .then(async (user)=>{
                      const response = await fetch('myAPi=' + userData.id );
                      const responseJson = await response.json();
                      this.setState({ dataSource: responseJson})
                    })
                }
              }
    
              render() {
                return (
                  <View>
                    <Text>{this.state.dataSource[0]['name']}</Text>
                    <TextInput
                      style={{ height: 40, borderColor: 'gray', borderWidth: 1 }} 
                      onChangeText={text => onChangeText(text)}
                      value={this.state.dataSource[0]['name']}
                    />
                    <TextInput
                      style={{ height: 40, borderColor: 'gray', borderWidth: 1 }} 
                      onChangeText={text => onChangeText(text)}
                      value={this.state.dataSource[0]['email']}
                    />
                  </View>
                );
              }
            }
    

    【讨论】:

    • 是的,但这不显示 name.throw 错误 undefined is not an object (evalating 'this.state.dataSource[0]['name']')
    • 可能是因为你的数据!看看这个:facebook.github.io/react-native/docs/textinput
    • 所以是componentdidmount问题。 setState 之后的数据源里面是什么?
    • 数据源数组[对象{“id”:“1”,“is_admin”:“1”,“is_superseller”:“0”,“jobtitle”:“导演”,“lastlogin”:“ 2019-09-30 07:08:57”,“登录数”:“27267”,“手机”:“9871323193”,“手机1”:“fdfd”,“姓名”:“Anshul Gupta”,“密码”:“ ss1234554321pl", }, ]
    • @DivyaLal 错误可能是由于在初始渲染中当时没有可用数据。为了避免错误,简单的解决方案是 Text ===>{this.state.dataSource [0] && this.state.dataSource[0]['name']} 和对于 TextInput ====> value={this.state.dataSource[0] && this.state.dataSource[0] ['name']} 或 value===>{this.state.dataSource[0] ? this.state.dataSource[0]['name']:" "}
    【解决方案3】:

    如果您想在文本输入中预填充来自 API 的名称值,只需在 API 获取用户信息后使用 this.setState 设置输入值。

    //Your state 
    
    this.state = {
    text: ''
    }
    
    // Your text input
    
          <TextInput
            onChangeText={text => this.setState({text})}
            value={this.state.text}
          />
    
    // Now when your component loads check if user data is in Async storage otherwise call API.Instead of using await you can use .then and set state after receiving the json.
    
        AsyncStorage.getItem('user').then(user => {
          fetch('myAPi=' + userData.id)
            .then(res => res.json())
            .then(responseJson => this.setState({ dataSource: responseJson, text: responseJson.name }));
        });
    
    

    我还建议不要使用 AsyncStorage 来存储用户数据,因为它是完全未加密的,但您可以调用。

    【讨论】:

    • 在文本输入中没有得到任何值
    • 您能提供完整的组件代码吗?我认为这将使调试更容易。否则在尝试此处建议的许多解决方案时很容易出现语法错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多