无法读取属性' propertyName'未定义的

时间:2018-01-28 19:41:46

标签: reactjs react-native react-props

我正在使用react-native处理一个项目,我在访问对象数组中的元素时遇到麻烦,方法是将其作为我想要使用它的prop。要求是获取name属性并将其设置为平面列表中的文本。

我的对象数组的结构如下。

return (
        <View>
           <AlbumDetail data = {this.state.allData}/>
        </View>
    );

这是如何将此对象数组作为我希望它使用的道具传递

 const AlbumDetail = (props) => {
 return (

 <View>
    {console.log(props.data[0])} //Working
    {console.log(props.data[0].media1[0].name)} //Not working

    // Requirement as bellow
    <Text>{wants to set the "name" here}</Text> 
    <Text>{wants to set the "price" here}</Text> 
 </View>   
);
};

这是我希望它被使用的地方

tbl_facts (Option_Name, Option_Value)
tbl_employees (Employee_ID, Name, Salary)
tbl_projects (Project_ID, Name, Manager_ID, Revenue)

我怎样才能实现这个目标?

2 个答案:

答案 0 :(得分:-1)

您可能想要放置两个缺少的逗号。 一个人:

{"name":"Michelle"}

之后

{"price":"76"}

答案 1 :(得分:-1)

  1. AlbumDetail无法知道它有一个名为data的属性。您需要将AlbumDetail函数编写为React.Component类。
  2. 您正在将JSON对象传递给AlbumDetail,您需要在使用它之前调用JSON.parse(data)。更新:.then(resp => resp.json())用于解析json。
  3. 返回前放置console.log。您返回的对象应该是纯JSX组件。
  4. 以下代码可以解决您的问题:

    import React from 'react';
    import { StyleSheet, Text, View } from 'react-native';
    
    const url =
      'http://purelight-prod.appspot.com/api/user/v2/browse/homescreendata';
    export default class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          data: undefined,
        };
      }
      componentDidMount() {
        fetch(url)
          .then(resp => resp.json())
          .then(respJson => {
            this.setState({
              data: respJson,
            });
          })
          .catch(err => {
            console.error(err);
          });
      }
      render() {
        return (
          <View style={{ flex: 1 }}>
            <TestView data={this.state.data} />
          </View>
        );
      }
    }
    
    class TestView extends React.Component {
      render() {
        !!this.props.data && console.log(console.log(data[0].healer[0].healerid));
        return (
          <View>
            <Text>Hello World!</Text>
          </View>
        );
      }
    }
    

    修改

    使用componentDidMount(),因为我们喜欢显示某些内容(加载图标等),然后在数据到达时更新View。

    这是一项异步任务。数据必须保留到它到达。我使用!!this.props.data && ...,因此它仅在未定义时显示。

    由于API响应是一个相对较大的包,因此如果使用TypeScript并创建一个对象类来解析它,它将更容易使用。

    我不认为API帮助程序包会在您的代码中提供正确的响应。

相关问题