【问题标题】:Is it possible to have more than one parameters in data for a FlatList?FlatList 的数据中是否可以有多个参数?
【发布时间】:2019-01-25 12:18:49
【问题描述】:

例如这样:

<FlatList data={ this.state.foods, this.state.trees }
          renderItem={({item}) => <View><Text>{item.food}</Text><Text>{item.tree}</Text></View>
/>

只要我有相同的密钥 (id),是否可以这样工作?

this.state.foods:

[{
  "id": "1",
  "food":"chicken",
  "cal":"1000",
}]

this.state.trees:

[{
  "id": "1",
  "tree":"pine",
  "size":"10",
}]

编辑:

    render(){
      const {trees, foods} = this.state
const combinedArray = trees.map(tree => Object.assign(tree, foods.find(food => food.id == tree.id)));
      return(




    componentDidUpdate(prevProps, prevState) {
      if (!prevState.foods) {

        fetch('https://www.example.com/React/food.php')
         .then((response) => response.json())
         .then((responseJson) => {
           this.setState({
             isLoading: false,
             foods:  responseJson.map(item => ({ ...item, progress: new Animated.Value(0), unprogress: new Animated.Value(1) }))

             }, function() {

           });
         })
         .catch((error) => {
           //console.error(error);
         });
         fetch('https://www.example.com/React/tree.php')
            .then((response) => response.json())
            .then((responseJson) => {
              this.setState({
                isLoading: false,
                trees:  responseJson
                }, function() {

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

【问题讨论】:

    标签: json reactjs react-native jsx


    【解决方案1】:

    您需要为Flatlist data 提供一个array

    您可以根据id 对对象进行分组并使用它们

    const {trees, foods} = this.state
    const combinedArray = trees.map(tree => Object.assign(tree, foods.find(food => food.id == tree.id)));
    

    然后在Flatlist中使用combinedArray

    如果您的state 最初是undefinednull,那么您需要添加

    constructor(props) {
        super(props)
        this.state = {
          trees: [],
          foods: []
        }
       }
    

    到你的类组件。

    【讨论】:

    • 好的,我完成了对我的代码的实现,我收到了这个错误:undefined is not an object (evalating 'trees.map')
    • 您能否发布完整的func 您使用该对象的位置,以及您如何初始化状态。
    • 同时添加initial state 定义。
    • 对不起,你是什么意思?你的意思是我从哪里获取它并将其更改为 this.state?
    • initial state,你在其中初始化了你的state,可以是constructor,也可以直接作为class variable
    猜你喜欢
    • 1970-01-01
    • 2020-12-30
    • 2020-05-16
    • 1970-01-01
    • 2020-01-10
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多