如何在React Native中发布数据?

时间:2019-09-18 08:42:49

标签: reactjs react-native

我已经编写了此代码以将数据发布到url中,但无法正常工作,这是我的Json文件

[{
        "id": 9,
        "questionnairename": "sfdsdf",
        "created_at": null,
        "updated_at": null,
        "questionnairecontent": null,
        "answername": null,
        "mosha": null,
        "gjinia": null,
        "komuna": null,
        "emri": null,
        "email": null,
        "importanttopics": null,
        "selectedparties": null,
        "session": null
    }, {
        "id": 10,
        "questionnairename": null,
        "created_at": null,
        "updated_at": null,
        "questionnairecontent": null,
        "answername": null,
        "mosha": null,
        "gjinia": null,
        "komuna": null,
        "emri": null,
        "email": null,
        "importanttopics": null,
        "selectedparties": null,
        "session": null
    },

这是我的代码:

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

export default class App extends Component {
  state = {
    // data: [],
    text:"",
    questionnairename:""

  };

  postData=async()=>{
    let anketaData = new anketaData();
    anketaData.append("id","0");
    anketaData.append("questionnairename","ermira");

    this.setState({text:"ermira"})
    fetch("http://192.168.0.100:8000/anketa/testd?method=get",{
      method:"POST",
      body:anketaData
    }).then((response)=>response())
    .then((responseJson)=>{
      this.setState({text:JSON.stringify(responseJson)})
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <Button onPress={this.postData} title="Post data"></Button>
        <Text>{this.state.text}</Text>
        <FlatList
          data={this.state.data}
          keyExtractor={(x, i) => i}
          renderItem={({ item }) =>
            <Text>
              {item.questionnairename} 
            </Text>}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    marginTop: 15,
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  }
});

这是错误:

  

“可能的未处理的承诺拒绝(id:0)”:   TypeError:未定义不是构造函数(正在评估“ new anketaData()”)

2 个答案:

答案 0 :(得分:0)

let anketaData = new anketaData()替换为

var formData = new FormData();

  • 您还可以使用以下方法发布数据

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});

答案 1 :(得分:0)

method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
mosha: TextInputName,
komuna: TextInputEmail,
emri: TextInputPhoneNumber
})
}).then((response) => response.json())
.then((responseJson) => {
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});