在 React to State 中解析 JSON 响应

Parsing JSON response in React to State

我有一个 API,它向我发送了一个 JSON,我想用它填充我的状态,但有些变量名称不同。我必须单独做所有事情还是有一种方法可以一次完成所有这些事情?

我的 JSON 来自请求:

{
   "name":"julps",
   "place": "house",
   "number":"555032",
   ...
   "products":[
      {
         "name":"name1",
         "id":"123456"
      },
      {
         "name":"name2",
         "id":"234567"
      }
   ],
}

我的状态:

this.state = {
  name: '',
  place: '',
  phone: '',
  ...
  things: []
};

获取请求:

  fetchEditData = (code) => {
    installationDocumentRequestApi(`/${code}`)
      .then((importedJson) => {
        if (importedJson != null) {
          this.setState({
            name: importedJson.name,
            place: importedJson.place,
            phone: importedJson.number,
            ...
            things: importedJson.products
          });
        }
      });
  };

在这个例子中,单独做它们会很好,但在我的实际例子中,我有大约 20 个字段,所以我开始想知道是否有更短的方法来做它或者它是唯一可能的解决方案。 另外,如果我可以使用所有相同的名称,那么它可以在不单独设置它们的情况下工作吗?

Do I have to do everything separately or is there a method to do all of them at once?

您不必单独执行所有操作。是的,您有办法一次获得所有这些。

我建议你用你所有的数据做一个状态。然后您将通过它访问您的数据。

例如:

this.state = {
  data: null
};

... 

fetchEditData = (code) => {
    installationDocumentRequestApi(`/${code}`)
      .then((importedJson) => {
        if (importedJson != null) {
          this.setState({
            data: importedJson
          });
        }
      });
  };

然后你可以得到你的状态数据。例如这样 console.log(data.name).

正如@evolutionxbox 在评论中提到的那样,您最好使用扩展语法 this.setState({ ...importedJson })