【问题标题】:Iteration over the state object迭代状态对象
【发布时间】:2020-08-01 10:43:57
【问题描述】:

我将一些数据存储在 AsyncStorage 中,然后将其放入 componentdidmount 并设置状态。到这里我做得很好,但我无法遍历数据以在平面列表组件中显示它。

状态和 componentDidMount 代码

class Cart extends React.Component {
  state ={ cart:"" }

  async componentDidMount(){
    const item = await AsyncStorage.getItem('cart')
    this.setState({cart:JSON.parse(item)})
  }

this.state.cart 我得到了这个对象

Object {
  "cart": Array [
    Object {
      "count": 1,
      "key": "NK01",
      "name": "Mohanjo Beaded Choker",
      "pic": "img1",
      "price": "1200",
    },
    Object {
      "count": 1,
      "key": "ID01",
      "name": "Silver Glass",
      "pic": "img3",
      "price": "9400",
    },
    Object {
      "count": 1,
      "key": "ID03",
      "name": "Ganesh With Kalash",
      "pic": "img2",
      "price": "3570",
    },
  ],
  "total": 3,
}

我想遍历this.state.cart.cart,但是当我使用 map 函数时,它会抛出一个错误,表明这不是一个函数。检查它的类型显示对象并且 Array.isArray 显示为 true 但这无法获取长度和迭代。

【问题讨论】:

    标签: arrays react-native object asyncstorage


    【解决方案1】:

    this.state.cart 是一个数组,所以你可以使用 map 函数来显示数组的元素:

    class Cart extends React.Component {
      state ={ cart:[] }
    
      async componentDidMount(){
        const item = await AsyncStorage.getItem('cart')
        this.setState(JSON.parse(item))
      }
    
    this.state.cart?.map(cart =>
            <div key={cart.key}>
              <h4>{cart.name}</h4>
              <p>{cart.price}</p>
            </div>
          );
    

    【讨论】:

    • this.state.cart.map 显示它不是函数的错误
    猜你喜欢
    • 2021-12-20
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2019-06-02
    • 1970-01-01
    • 2014-05-08
    相关资源
    最近更新 更多