反应原生阵列映射错误

时间:2018-06-15 14:00:10

标签: reactjs react-native

我似乎遇到了我正在构建的React Native应用程序的问题。我传递一个对象数组作为组件的prop并尝试映射数组。以下是数组的示例:

[{"title":"test"},{"title":"test"},{"title":"test"}]

我可以输出整个数组,但是如果我尝试映射数组,我会收到此错误:

TypeError: undefined is not a function (evaluating 'this.props.history_data.map')

这是我的容器渲染功能:

render() {
return (
  <View>
    <Text>
      {this.props.history_data.map(route => {
          return (
            <Text key={route.title}>{route.title}</Text>
          );
        })
      }
    </Text>
  </View>
);
}

长时间在桌子上敲我的头。是时候寻求帮助了。提前谢谢!

4 个答案:

答案 0 :(得分:0)

不确定这是否是您的问题。但是它是一个机会。如果您的组件呈现时this.props.history_data始终为undefined,那么您将在.map上呼叫undefined时收到错误,这显然没有.map方法。尝试进行空检查吗?

render() {
    return (
        <View>
            <Text>
                {this.props.history_data && this.props.history_data.length ?
                    this.props.history_data.map(route => {
                        return (
                            <Text key={route.title}>{route.title}</Text>
                        );
                    }) : null // either set as null or render another component when it's undefined or of zero length
                }

            </Text>
        </View>
    );
}

答案 1 :(得分:0)

试试这个

render() {
  let routes = this.props.history_data.map(route => {
                    return (
                        <Text key={route.title}>{route.title}</Text>
                    );
                })
  return (
    <View>
        <Text>
            {routes}
        </Text>
    </View>
);

}

答案 2 :(得分:0)

我从未弄清楚为什么我的代码无效。我认为这是某种形式的作为道具被异步从AsyncStorage由父组件加载,然后使用的setState传递到子组件传递的数据时序问题。

我最终重新启动组件以直接从AsyncStorage获取数据,而不是从父组件接收它作为prop。

谢谢大家帮助我思考这个问题!

答案 3 :(得分:-1)

不太确定,但你可以试试这个

{this.props.history_data.map( 
  (route) => { 
     return ( <Text key={route.title}>{route.title}</Text> ); 
   })
}

router =>应为(router) =>

相关问题