Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取内部获取错误setState_Javascript_Reactjs - Fatal编程技术网

Javascript 获取内部获取错误setState

Javascript 获取内部获取错误setState,javascript,reactjs,Javascript,Reactjs,我在解决这个react.js时遇到了一个问题 loadFromServer(pageSize) { fetch('http://localhost:8080/api/employees') .then(response => { return fetch('http://localhost:8080/api/profile/employees', { headers: new

我在解决这个react.js时遇到了一个问题

loadFromServer(pageSize) {

        fetch('http://localhost:8080/api/employees')
        .then(response => {
            return fetch('http://localhost:8080/api/profile/employees',
            {
                headers: new Headers({
                'Accept': 'application/schema+json'
              })
            }).then(schema => {
                this.scheme =  schema;
                return response.json();
            }   
            )

       })
        .then(response =>             
            this.setState(
                {
                employees: response._embedded.employees,
                attributes: Object.keys(this.scheme.json().properties),
                pageSize: pageSize,
                links: response._links}                      
            )
        );          
    }
在这一部分

attributes: Object.keys(this.scheme.json().properties),
始终返回承诺类型错误:无法将未定义或null转换为对象

如果我放置console.logthis.scheme.json,我可以看到承诺,但是为什么在setState中我会得到null对象?

Fetch API中的响应json方法。因此,获取请求应始终与.thenresponse=>response.json链接,以获取普通对象

扁平化承诺可能会导致更可靠的控制流。由于使用了来自两个请求的响应,这将需要嵌套然后回调,或者通过然后链传递另一个响应。async可能很有用,因为它可以方便地解决扁平化问题:

async loadFromServer(pageSize) {
    const employeesResponse = await fetch('http://localhost:8080/api/employees', {
      headers: new Headers({ 'Accept': 'application/schema+json' })
    });
     const employees = await employeesResponse.json();

    const schemeResponse = await fetch('http://localhost:8080/api/profile/employees', {
      headers: new Headers({ 'Accept': 'application/schema+json' })
    });
    const scheme = await schemeResponse.json();

    this.setState({
        employees: employees._embedded.employees,
        attributes: Object.keys(scheme.properties),
        pageSize: pageSize,
        links: response._links
    });
}
由于请求互不依赖,因此它们可以与Promise.all并行执行

获取API中的响应json方法。因此,获取请求应始终与.thenresponse=>response.json链接,以获取普通对象

扁平化承诺可能会导致更可靠的控制流。由于使用了来自两个请求的响应,这将需要嵌套然后回调,或者通过然后链传递另一个响应。async可能很有用,因为它可以方便地解决扁平化问题:

async loadFromServer(pageSize) {
    const employeesResponse = await fetch('http://localhost:8080/api/employees', {
      headers: new Headers({ 'Accept': 'application/schema+json' })
    });
     const employees = await employeesResponse.json();

    const schemeResponse = await fetch('http://localhost:8080/api/profile/employees', {
      headers: new Headers({ 'Accept': 'application/schema+json' })
    });
    const scheme = await schemeResponse.json();

    this.setState({
        employees: employees._embedded.employees,
        attributes: Object.keys(scheme.properties),
        pageSize: pageSize,
        links: response._links
    });
}
由于请求互不依赖,因此它们可以与Promise.all并行执行


这里有几个问题:

主要的一点是this.schema.json返回一个承诺,正如您从console.log知道的那样。承诺没有properties属性,因此您将未定义的传递给Object.keys,这将导致错误。 您也没有通过两种不同的方式检查fetch中的错误:您没有检查。好的,这是一种常见的错误,您没有检查承诺拒绝。 您还进行了一些不必要的承诺嵌套,并且可能会更多地重叠您的获取调用

首先,由于您似乎经常获取JSON,我建议您为它提供一个实用函数:

function fetchJSON(...args) {
    return fetch(...args)
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP error ' + response.status);
            }
            return response.json();
        });
}
注意。好的,检查一下

然后,在“将问题分解为更小的部分”类别中,我有一个fetchSchema函数:

function fetchSchema(url) {
    return fetchJSON(url, {
        headers: new Headers({
            'Accept': 'application/schema+json'
        })
    });
}
然后,loadFromServer可以使用Promise.all和destructuring并行运行操作:

// (I assume this is in a `class` or object initializer, as it doesn't have `function` in front of it)
loadFromServer(pageSize) {
    Promise.all(
        fetchJSON('http://localhost:8080/api/employees'),
        fetchSchema('http://localhost:8080/api/profile/employees')
    )
    .then(([empResponse, schema]) => {
        this.schema = schema;
        this.setState({
            employees: empResponse._embedded.employees,
            attributes: Object.keys(schema.properties),
            pageSize: pageSize,
            links: empResponse._links
        })
    )
    .catch(error => {
        // Do something with the error
    });
}
注意.catch,因为您没有从loadFromServer返回承诺。如果您想减少错误,请在Promise.all前面添加return,并将.catch移动到调用代码

旁注:您使用的代码

this.scheme =  schema;

请注意,左侧的属性是带有最终e的scheme,但变量是带有最终a的schema。我想你指的是schema,所以我在上面包含了这个更改,但是如果属性真的应该是this.scheme,那么你需要调整它。或者,如果除了loadFromServer中的代码之外,您不需要该属性,请完全删除该行。

这里有一些问题:

主要的一点是this.schema.json返回一个承诺,正如您从console.log知道的那样。承诺没有properties属性,因此您将未定义的传递给Object.keys,这将导致错误。 您也没有通过两种不同的方式检查fetch中的错误:您没有检查。好的,这是一种常见的错误,您没有检查承诺拒绝。 您还进行了一些不必要的承诺嵌套,并且可能会更多地重叠您的获取调用

首先,由于您似乎经常获取JSON,我建议您为它提供一个实用函数:

function fetchJSON(...args) {
    return fetch(...args)
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP error ' + response.status);
            }
            return response.json();
        });
}
注意。好的,检查一下

然后,在“将问题分解为更小的部分”类别中,我有一个fetchSchema函数:

function fetchSchema(url) {
    return fetchJSON(url, {
        headers: new Headers({
            'Accept': 'application/schema+json'
        })
    });
}
然后,loadFromServer可以使用Promise.all和destructuring并行运行操作:

// (I assume this is in a `class` or object initializer, as it doesn't have `function` in front of it)
loadFromServer(pageSize) {
    Promise.all(
        fetchJSON('http://localhost:8080/api/employees'),
        fetchSchema('http://localhost:8080/api/profile/employees')
    )
    .then(([empResponse, schema]) => {
        this.schema = schema;
        this.setState({
            employees: empResponse._embedded.employees,
            attributes: Object.keys(schema.properties),
            pageSize: pageSize,
            links: empResponse._links
        })
    )
    .catch(error => {
        // Do something with the error
    });
}
注意.catch,因为您没有从loadFromServer返回承诺。如果您想减少错误,请在Promise.all前面添加return,并将.catch移动到调用代码

旁注:您使用的代码

this.scheme =  schema;

请注意,左侧的属性是带有最终e的scheme,但变量是带有最终a的schema。我想你指的是schema,所以我在上面包含了这个更改,但是如果属性真的应该是this.scheme,那么你需要调整它。或者,如果除了loadFromServer中的代码之外,您不需要该属性,请完全删除该行。

我认为您需要类似以下内容:

loadFromServer(pageSize) {
  fetch('http://localhost:8080/api/employees')
    .then(response => {
      return fetch('http://localhost:8080/api/profile/employees', {
        headers: new Headers({
          'Accept': 'application/schema+json'
        })
      }).then(schema => {
        schema.json().then(data => {
          this.scheme = data
        })
      });
      return response.json();
    })
    .then(response =>
      this.setState({
        employees: response._embedded.employees,
        attributes: Object.keys(this.scheme.properties),
        pageSize: pageSize,
        links: response._links
      })
    );
}

我想你需要这样的东西:

loadFromServer(pageSize) {
  fetch('http://localhost:8080/api/employees')
    .then(response => {
      return fetch('http://localhost:8080/api/profile/employees', {
        headers: new Headers({
          'Accept': 'application/schema+json'
        })
      }).then(schema => {
        schema.json().then(data => {
          this.scheme = data
        })
      });
      return response.json();
    })
    .then(response =>
      this.setState({
        employees: response._embedded.employees,
        attributes: Object.keys(this.scheme.properties),
        pageSize: pageSize,
        links: response._links
      })
    );
}
我认为您应该使用Promise.all在Parralel中运行这两个请求,然后通过response.json返回承诺的方式检索这两个响应,这就是代码中出现错误的原因:

loadFromServer(pageSize) {
    Promise.all([
        fetch('http://localhost:8080/api/employees')
        .then(response => {
           if (!response.ok) throw Error(response.statusText);
           return response.json();
        ),
        fetch('http://localhost:8080/api/profile/employees')
        .then(response => {
           if (!response.ok) throw Error(response.statusText);
           return response.json();
        ),
    ]).then(responses => {
        this.setState({
          employees: responses[0]._embedded.employees,
          attributes: Object.keys(responses[1].properties),
          pageSize: pageSize,
          links: responses[0]._links
        })
    }).catch(error => {...})        
}
我认为您应该使用Promise.all在Parralel中运行这两个请求,然后通过response.json返回承诺的方式检索这两个响应,这就是代码中出现错误的原因:

loadFromServer(pageSize) {
    Promise.all([
        fetch('http://localhost:8080/api/employees')
        .then(response => {
           if (!response.ok) throw Error(response.statusText);
           return response.json();
        ),
        fetch('http://localhost:8080/api/profile/employees')
        .then(response => {
           if (!response.ok) throw Error(response.statusText);
           return response.json();
        ),
    ]).then(responses => {
        this.setState({
          employees: responses[0]._embedded.employees,
          attributes: Object.keys(responses[1].properties),
          pageSize: pageSize,
          links: responses[0]._links
        })
    }).catch(error => {...})        
}

那么,如何让响应second fetch->schema放入setState?对于ES6,这通常涉及嵌套的Then或通过Then传递响应
使用扩展/解构语法,或将它们分配给父范围中的临时变量。通过异步更新答案,这将变得更加简单。希望这有帮助。那么我如何让响应二次获取->模式放入setState?对于ES6,这通常涉及嵌套的Then,或者使用扩展/解构语法通过Then传递响应,或者将它们分配给父范围中的临时变量。通过异步更新答案,这将变得更加简单。希望这有帮助。为什么我们需要这个。schema=schema;还有吗@ArupRakshit:我假设这是一个方法,拥有这个属性很重要。当然,如果OP不需要这个属性,他们应该删除它。我同意。但我假设OP将其存储到该文件中,以便稍后访问,但OP从错误消息中意识到,这一基本原理是错误的。因此,可能不再需要它了。。无论如何,这是OP的电话。我只是想在这里做个记录是的。。如果在抓取时发生了什么事情,那么使用catcherror是很重要的..谢谢为什么我们需要这个。schema=schema;还有吗@ArupRakshit:我假设这是一个方法,拥有这个属性很重要。当然,如果OP不需要这个属性,他们应该删除它。我同意。但我假设OP将其存储到该文件中,以便稍后访问,但OP从错误消息中意识到,这一基本原理是错误的。因此,可能不再需要它了。。无论如何,这是OP的电话。我只是想在这里做个记录是的。。如果在获取..thanksyups..时发生问题,则使用catcherror非常重要。。使用promise.all是处理pararel获取的优雅方式…非常感谢。它还忽略了获取中的错误,这些错误最终会变成未经处理的承诺拒绝。是的,顺便说一句,我不太喜欢获取api,我更喜欢使用axios,我认为axios更易于使用。。使用promise.all是处理pararel获取的优雅方式…非常感谢。它还忽略了获取中的错误,这些错误最终会变成未处理的承诺拒绝。是的,顺便说一句,我不太喜欢获取api,我更喜欢使用axios,我认为它更易于使用