【问题标题】:How to send react native text field value as JSON.stringify如何将本机文本字段值作为 JSON.stringify 发送
【发布时间】:2021-05-24 05:39:09
【问题描述】:

我有这样的代码:-

export default class TextField extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userID: '',
      userName: '',
      userGmail: '',
      userTNumber: '',
    };
  }
  addCustomer = () => {
    fetch('http://localhost:3000/send-data', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({}),
    });
  }         <TextInput
            style={styles.inputText}
            placeholder="User ID :"
            placeholderTextColor="#ffff"
            onChangeText={userID => this.setState({userID})}
            value={this.state.userID}
            autoCapitalize="none"
          />
        </View>
}

我需要将我的文本输入发送到我的节点后端... 我不知道如何使用这个 Fetch 函数发送我的数据

**

addCustomer = () => {
    fetch('http://localhost:3000/send-data', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({}),
    });
  };

**

我不知道如何输入我的文本输入,

 body: JSON.stringify({}),

这是我发布数据的后端:-

app.post('/send-data', (req, res) => {
  const customer = new Customer({
    userID: req.body.userID,
    userName: req.body.userName,
    userGmail: req.body.userGmail,
    userTNumber: req.body.userTNumber,
  });
  customer
    .save()
    .then(result => {
      console.log(result);
      res.send(result);
    })
    .catch(err => {
      console.log(err);
    });
});

你能帮我吗..? 谢谢你..!

【问题讨论】:

  • 您希望如何在后端接收数据?它应该如何构建?请使用一些有效请求有效负载的示例更新帖子。
  • 我更新我的帖子

标签: node.js reactjs react-native


【解决方案1】:

如果我理解正确,您希望按以下格式传递数据:

{
  "userID": 1,
  "userName": "John Doe",
  "userGmail": "john.doe@example.com",
  "userTNumber": "1234"
}

您想使用您所在州的数据并将其传递给fetch 函数,如下所示:

export default class TextField extends Component {
  constructor(props) {
    super(props)

    this.state = {
      userID: "",
      userName: "",
      userGmail: "",
      userTNumber: "",
    }
  }

  addCustomer = () => {
    const { userID, userName, userGmail, userTNumber } = this.state

    fetch("http://localhost:3000/send-data", {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ userID, userName, userGmail, userTNumber }),
    })
  }

  render() {
    return (
      <TextInput
        style={styles.inputText}
        placeholder="User ID :"
        placeholderTextColor="#ffff"
        onChangeText={(userID) => this.setState({ userID })}
        value={this.state.userID}
        autoCapitalize="none"
      />
    )
  }
}

【讨论】:

  • 非常感谢..!
猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 2021-02-25
  • 1970-01-01
  • 2021-05-15
  • 2022-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多