【问题标题】:React Native Array not working when passed as props to child componentReact Native Array 在作为道具传递给子组件时不起作用
【发布时间】:2017-06-16 12:27:53
【问题描述】:

我有一个包含数组的组件,我想将此数组传递给子组件,并使用 map 根据该数组的元素呈现项目。但是,当尝试将 map 与数组一起使用时,React 似乎无法将 prop 识别为数组,因为我收到以下错误:

未定义不是对象('Evaluating this.props.foodTagList.map')

所以它认为 map 是一个对象而不是一个函数......

简而言之,家长:

const food = { TagList:[
    {
        TagId: 4,
        TagName: "onion"
    },
    {
        TagId: 6,
        TagName: "beef"
    },
    {
        TagId: 7,
        TagName: "pork"
    },
    {
        TagId: 8,
        TagName: "carrot"
    },
    {
        TagId: 9,
        TagName: "fish"
    }
]};

<FoodTags foodTagList={food.TagList} />

和孩子:

export default class FoodTags extends React.Component{

constructor(props){
    super(props);
}

shouldComponentUpdate(nextProps, nextState){
    return false;
}

render(){
    return <View style={layoutStyles.tagWrapper}>
        {this.props.foodTagList.map((x, i) => {
            return( <Tag key={i} info={this.props.foodTagList[i]} />)
        })}
    </View>
}

}

class Tag extends React.Component{
constructor(props){
    super(props);
}

render(){
    return <Text style={foodStyles.tag}>{this.props.info.TagName}</Text>
}

}

所以我的问题是:如何正确地将数组传递给子组件?

【问题讨论】:

  • 嗯,这是我在写问题时犯的一个错字。它不存在于我的代码中,显然不是错误的根源。问题仍然存在。当我将数组作为道具传递时,孩子不再将其视为数组。顺便说一下。使用 x[i] 代替 this.props.foodTagList[i] 也不起作用。
  • 你是从服务器获取数据还是硬编码?不要使用info={this.props.foodTagList[i]} 使用info={x} x 不需要索引。
  • “所以它认为 map 是一个对象而不是一个函数......”不,它认为 this.props.foodTagListundefined。指定FoodTags组件static propTypes = {foodTagList: PropTypes.array.isRequired}的属性类型,看看哪个组件传递了错误的props。
  • @SimonEliasson 代码看起来应该可以工作。你真的需要弄清楚props.foodTagList上的未定义在哪里,你能告诉我this.props.foodTagList.isArray()的结果吗?
  • 感谢您的所有回答。学到了很多。我会删除帖子。我用 x 语法进行了测试,并摆弄了 proptypes,突然它起作用了。但我无法准确指出解决方案是什么,因为当我撤消更改时它仍然有效。所以可能我在某处有一些语法错误。很抱歉浪费了您的时间,但是您留下的 cmets 仍然帮助我修复了它,所以谢谢!取消删除它。我不知道应该怎么做。

标签: reactjs react-native


【解决方案1】:

当您最初渲染时,我感觉foodTagList 实际上是undefined,因为您有return false,所以您根本没有得到数据。如果它认为map 是一个对象而不是一个函数,你会得到Uncaught TypeError: map is not a function 或类似的东西。您可以尝试在shouldComponentUpdate 中返回true

【讨论】:

  • shouldComponentUpdate 在这种情况下不是问题。
猜你喜欢
  • 2022-01-24
  • 2021-05-26
  • 2017-11-19
  • 2018-03-26
  • 2017-04-30
  • 2018-06-04
  • 2018-08-01
  • 2020-04-22
相关资源
最近更新 更多