繁体   English   中英

通过AsyncStorage React-native输入数据时出错

[英]Getting error while entering data via AsyncStorage React-native

尝试放入购物车系统的数据时出现错误。

我可以在尝试[json];时放入数据[json]; 但是当我将其更改为[...json];时无法执行[...json];

[json]; 给我我最后放的东西,但我需要所有这些

addCart=()=>{



  const sepets = AsyncStorage.getItem("sepet")
   .then(req => {
   const json =  JSON.parse(req); 
   const sepet=[...json];
   sepet.push({isim:this.props.title,fiyat:this.props.fiyat,image:this.props.image});

   AsyncStorage.setItem("sepet",JSON.stringify(sepet));


   });




    }

给我的错误“可能的未处理的承诺拒绝(id:0):TypeError:尝试传播不可迭代的实例无效尝试TypeError:尝试在_nonIterableSpread传播不可迭代实例无效”

我要删除此类导出默认类,例如aksiyos扩展了React.Component {

        constructor(props) {
        super(props);
        this.state = {
          ApiTitle: [],
        }
      }

          componentDidMount() {


       var sepet=AsyncStorage.getItem("sepet").then(req=>JSON.parse(req)).then(json=>{

      this.setState({ApiTitle: json });


       });




      }

      removeCart=()=>{

        AsyncStorage.removeItem("sepet")
      }
        render() {
        return (
          <View style={{backgroundColor: "white"}}>
          <ScrollView>{this.state.ApiTitle.map((ids, i)=>

            <Text>{ids.isim}</Text>


    )}
            </ScrollView>
                            <Text onPress={this.removeCart}>Buton</Text>
            </View>
        );
      }
     }

`

解析数据时.then()不需要多余的.then() 您还需要检查是否为null,删除项目后,getItem将返回null。

const sepets = AsyncStorage.getItem("sepet")
 .then(req => {

 let json =  JSON.parse(req);

 if (!json) {
   json = [];
 }

 const sepet=[...json];
 sepet.push({isim:this.props.title,fiyat:this.props.fiyat,image:this.props.image});

 AsyncStorage.setItem("sepet",JSON.stringify(sepet));

 console.log(sepet)

 });

在渲染中使用ApiTitle之前对其进行验证。

render() {

  const items = this.state.ApiTitle || [];

  return (
    <View style={{ backgroundColor: "white" }}>
      <ScrollView>{items.map((ids, i) =>
        <Text>{ids.isim}</Text>
      )}
      </ScrollView>
      <Text onPress={this.removeCart}>Buton</Text>
    </View>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM