首页 > 解决方案 > JSON.stringify 在传递状态时无法序列化循环结构

问题描述

在 react-native 中获取数据时出现问题。我正在尝试在 POST 正文中发送我的部分状态。我不明白我的代码中的循环结构在哪里。我没有看到任何循环结构。

我知道错误是由状态引起的,因为当我简单地将一些字符串放入正文时,一切都会好起来的。

import React from 'react';

import {Text, View, Button, StyleSheet, TextInput, TouchableOpacity} from "react-native";

export default class AddKidScreen extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            name: '',
            age: '',
            parentID: props.navigation.getParam('myID', 0)
        }
    }

    handleAddKid() {
        let url = "https://piotr2.scementowani.pl/apiPiotr";
        let name = this.state.name;
        let age = this.state.age;
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': "application/json",
            },
            body: JSON.stringify({
                method: "addKid",
                name: name,
                age: age,
            }),
        })
            .then(response => response.json())
            .then(responseJson => {
                this.props.navigation.navigate('Main');
            })
            .catch((error) => {
                console.error(error);
            });
    }

    updateValue(text,field) {
        if (field == 'name') {
            this.setState({
                name: text,
            })
        } else if (field == 'age' ){
            this.setState( {
                age: text,
            })
        }
    }

    render() {
        return(
            <View>
                <View style={{flexDirection: 'row', width: '100%'}}>
                    <Text>
                        Imię:
                    </Text>
                    <TextInput
                        placeholder = "Imię"
                        onChange = {(text) => this.updateValue(text,'name')}
                    />
                </View>
                <View style={{flexDirection: 'row', width: '100%'}}>
                    <Text>
                        Wiek:
                    </Text>
                    <TextInput
                        placeholder = "Wiek"
                        onChange = {(text) => this.updateValue(text,'age')}
                    />
                </View>
                <TouchableOpacity onPress={this.handleAddKid.bind(this)}>
                    <Text>DODAJ</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

运行 handleAddKid() 时

我得到 JSON.stringify 无法序列化循环结构。

标签: reactjsreact-native

解决方案


推荐阅读