【问题标题】:How to make an API request In React on button click如何在 React 点击按钮时发出 API 请求
【发布时间】:2019-08-29 15:59:33
【问题描述】:

我正在尝试构建一个随机报价生成器,它通过 axios api 请求在 componentDidMount 上加载报价,然后在单击按钮时加载新报价。

这是一个 freecodecamp 项目。我曾尝试在单击按钮时再次拨打电话,然后将新的响应添加到状态,但它根本不起作用。

    import React, { Component } from 'react'
    import Button from './Button';
    import axios from 'axios'
    class QuoteBox extends Component{
    constructor(props){
        super(props)

        this.state = {
          quotes: []

        }

     }
    componentDidMount(){
     axios.get('http://quotesondesign.com/wp-json/posts? 
    filter[orderby]=rand&filter[posts_per_page]=1')
     .then(res=> this.setState({quotes: res.data[0]}))

    }
    getNext = (ev) =>{
      ev.preventDefault()
      axios.get('http://quotesondesign.com/wp-json/posts? 
    filter[orderby]=rand&filter[posts_per_page]=2')
      .then(res=> this.setState({quotes:[...this.state,res.data[0]]}))
    }


    render(){
    const {content,title} = this.state.quotes
    const filteredContent = String(content).replace(/(<\w>)|(<\/\w>)| 
    (&#\d{4})/gm, "").replace(/(;)/g,"'")
     console.log(content)

     return(
       <React.Fragment>
          <h2>A little inspiration for the day</h2>
          <div className='outerQuoteBox'>
            <div className='innerQuoteBox'>
                <p>{filteredContent}</p><br/><br/>{title}
            </div>
            <Button getNext={this.getNext} />
        </div>
        </React.Fragment>)
       }
      }
    export default QuoteBox

这是我的按钮组件

   import React, { Component } from 'react'

   export class Button extends Component {
    render() {
     return (
      <React.Fragment>
       <button onClick={this.props.getNext} className='nextBtn' 
         type='button'>Next</button>
       </React.Fragment>
      )
    }
   }

   export default Button

当我单击按钮时,似乎请求根本没有通过。如果我在开发工具中检查状态,则只有 componentDidMount 的第一个引号在数组中。我不明白我的错误在哪里。

编辑:我使用了错误的道具参考,所以它没有打电话。我解决了这个问题,它现在确实打电话了,它带来了一个新的报价,但就是这样。它不会添加新的状态,它只是用一个新的替换它。这就是它所能做的。 api 指令说我使用的端点应该返回一个新的随机引用,但它没有。

【问题讨论】:

  • 按钮周围不需要 React.Fragment,它是单个元素
  • 谢谢,我一开始有多个按钮,后来改了忘记删除片段了。

标签: reactjs api axios


【解决方案1】:

您似乎在按钮上引用了错误的道具。

getQuote 更改为getNext,它应该可以工作...

import React, { Component } from 'react'

export class Button extends Component {
 render() {
  return (
   <React.Fragment>
    <button onClick={this.props.getNext} className='nextBtn' 
      type='button'>Next</button>
    </React.Fragment>
   )
 }
}

export default Button

【讨论】:

  • 哎呀,这是一张大脸Palm。你现在打电话是对的,但它只会带来一个新的报价,并且不会将第一个报价保存到状态。你知道是什么原因造成的吗?
猜你喜欢
  • 2013-04-20
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 2021-04-02
  • 2015-03-06
  • 1970-01-01
  • 2019-12-10
相关资源
最近更新 更多