Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.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 如何使用API来响应异步调用?_Javascript_Api_Reactjs - Fatal编程技术网

Javascript 如何使用API来响应异步调用?

Javascript 如何使用API来响应异步调用?,javascript,api,reactjs,Javascript,Api,Reactjs,所以我想用React把我的手弄脏。我下定决心要用ReactJS编写维基百科查看器项目。然而,在使用React组件从wikipedia的API获取数据后,我昨天遇到了麻烦。我认为这与异步调用有关 我定义了一个接受查询并将其注入API url的常量: javascript const apiUrl=query=> `https://crossorigin.me/https://en.wikipedia.org/w/api.php?action=opensearch&format=json&searc

所以我想用React把我的手弄脏。我下定决心要用ReactJS编写维基百科查看器项目。然而,在使用React组件从wikipedia的API获取数据后,我昨天遇到了麻烦。我认为这与异步调用有关

我定义了一个接受查询并将其注入API url的常量:
javascript
const apiUrl=query=>
`https://crossorigin.me/https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=${query}`
然后我定义了一个类,该类以ComponentDidMount状态异步获取API:

class Wiki extends React.Component {
constructor(props){
    super(props);
  console.log('Inside Constructor')
}
componentWillMount(){
  this.setState = {
    wikiData: undefined
  }
  console.log('Before fetch')
    fetch(apiUrl(this.props.query))
    .then(console.log('fetch successful'))
    .then(response => {
        if(!response.ok){
            throw Error("Response not ok")
        }
        return response
    })
    .then(data => data.json())
    .then(data => {
        this.setState ={
            wikiData: data
        }
      console.log(data)
    })

}
render(){
    if(!this.state.wikiData == null) return <p>No answer</p>
    else{
    return (
        <div>
            <h1>Something happened</h1>
        <h2>{this.state.wikiData[0]}</h2>
        </div>
    )
    }
}
类Wiki扩展了React.Component{
建造师(道具){
超级(道具);
console.log('内部构造函数')
}
组件willmount(){
this.setState={
wikiData:未定义
}
console.log('Before fetch')
fetch(apirl(this.props.query))
.then(console.log('fetch successful'))
。然后(响应=>{
如果(!response.ok){
抛出错误(“响应不正常”)
}
返回响应
})
.then(data=>data.json())
。然后(数据=>{
这是我的国家={
维基数据:数据
}
console.log(数据)
})
}
render(){
如果(!this.state.wikiData==null)返回无答案

否则{ 返回( 出事了 {this.state.wikiData[0]} ) } }
}

当我在应用程序组件中调用它时,我得到一个TypeError sying“Cannot read property'wikiData'of null”,之后数据从调用返回并且不再为null,但这会导致渲染中断。 我确实尝试过使用componentDidMount,但这也不起作用。 我不知道该怎么办,我想了解一下这个过程。 这是我的密码笔:


我想知道如何仅在调用API返回数据后渲染组件,以便在渲染之前访问和处理组件。

您在
componentWillMount
中键入了一个错误,您编写了
this.setState
而不是
this.state
。我还建议您将此声明提交给建造商:

class Wiki extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      wikiData: undefined
    }
  }
  ...
}

您在
组件willmount
中输入了一个错误,您编写了
this.setState
而不是
this.state
。我还建议您将此声明提交给建造商:

class Wiki extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      wikiData: undefined
    }
  }
  ...
}

您说的没错,在服务响应之前调用了render方法


因此,当wikiData字段未定义时,您必须通过显示加载微调器来调节呈现。当服务返回数据时,您将呈现wikiData。

您说的是,在服务响应之前调用了呈现方法


因此,当wikiData字段未定义时,您必须通过显示加载微调器来调节渲染。当服务返回数据时,您将渲染wikiData。

您的代码中有一些错误,让我扩展一下

首先,在类构造函数上应该有组件的默认状态,所以移动方法componentWillMount上的前三行

其次,您的默认状态是错误的:

this.setState = {
    wikiData: undefined
}

this.setState
是一个函数,要设置默认状态,您应该使用
this.state

您的代码中有一些错误,让我扩展一下

首先,在类构造函数上应该有组件的默认状态,所以移动方法componentWillMount上的前三行

其次,您的默认状态是错误的:

this.setState = {
    wikiData: undefined
}

this.setState
是一个函数,要设置默认状态,您应该使用
this.state

我对您的代码做了一些修改,并发表了一些评论,希望能对您有所帮助

class Wiki extends React.Component {

  constructor(props) {
    super(props);

    // this.state, not this.setState.
    // Also, it helps if you set your initial value to the value
    // to what you expect from your fetch (ie an array, albeit empty)
    this.state = { wikiData: [] }
  }

  // componentDidMount rather than componentWillMount
  // https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/
  componentDidMount() {
    fetch(apiUrl(this.props.query))
      .then(response => {
      .then(data => data.json())
      .then(data => this.setState = { wikiData: data }
      });
  }

  render() {

    // Check to see if your initial state is empty or not
    if (!this.state.wikiData.length) return <p>No answer</p>

    // No need for your else here. If your state is not empty, the first
    // return doesn't run, but this one does as a default.
    return (
      <div>
        <h1>Something happened </h1>
        <h2>{this.state.wikiData[0]}</h2>
      </div>
    )
  }

}
类Wiki扩展了React.Component{
建造师(道具){
超级(道具);
//this.state,而不是this.setState。
//此外,如果将初始值设置为
//到您期望的获取(即数组,尽管为空)
this.state={wikiData:[]}
}
//componentDidMount而不是componentWillMount
// https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/
componentDidMount(){
fetch(apirl(this.props.query))
。然后(响应=>{
.then(data=>data.json())
.then(data=>this.setState={wikiData:data}
});
}
render(){
//检查初始状态是否为空
如果(!this.state.wikiData.length)返回无答案

//这里不需要你的其他。如果你的状态不是空的,第一个 //return不会运行,但默认情况下会运行。 返回( 出事了 {this.state.wikiData[0]} ) } }
我对您的代码做了一些修改,并发表了一些评论,希望能对您有所帮助

class Wiki extends React.Component {

  constructor(props) {
    super(props);

    // this.state, not this.setState.
    // Also, it helps if you set your initial value to the value
    // to what you expect from your fetch (ie an array, albeit empty)
    this.state = { wikiData: [] }
  }

  // componentDidMount rather than componentWillMount
  // https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/
  componentDidMount() {
    fetch(apiUrl(this.props.query))
      .then(response => {
      .then(data => data.json())
      .then(data => this.setState = { wikiData: data }
      });
  }

  render() {

    // Check to see if your initial state is empty or not
    if (!this.state.wikiData.length) return <p>No answer</p>

    // No need for your else here. If your state is not empty, the first
    // return doesn't run, but this one does as a default.
    return (
      <div>
        <h1>Something happened </h1>
        <h2>{this.state.wikiData[0]}</h2>
      </div>
    )
  }

}
类Wiki扩展了React.Component{
建造师(道具){
超级(道具);
//this.state,而不是this.setState。
//此外,如果将初始值设置为
//到您期望的获取(即数组,尽管为空)
this.state={wikiData:[]}
}
//componentDidMount而不是componentWillMount
// https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/
componentDidMount(){
fetch(apirl(this.props.query))
。然后(响应=>{
.then(data=>data.json())
.then(data=>this.setState={wikiData:data}
});
}
render(){
//检查初始状态是否为空
如果(!this.state.wikiData.length)返回无答案

//这里不需要你的其他。如果你的状态不是空的,第一个 //return不会运行,但默认情况下会运行。 返回( 出事了 {this.state.wikiData[0]} ) } }
如果在解决
api
问题时,我移动到其他路线,会发生什么