【问题标题】:how to select random api by submit button in react如何通过反应中的提交按钮选择随机api
【发布时间】:2019-06-10 07:43:40
【问题描述】:

我通过单击按钮在 api 中选择随机数据,我的代码不起作用 代码需要在 submitChange 函数中的代码

export class MemeGenerator extends React.Component {
constructor (props) {
super(props)
this.state = {
  apiData: []
}
this.submitChange = this.submitChange.bind(this)
}
componentDidMount () {
fetch('https://api.imgflip.com/get_memes')
  .then(response => response.json())
  .then(data => {
   this.setState({
     apiData: data
    })
    console.log(this.state.apiData)
  })}

OnChange 函数?????

submitChange () {
}

并从 api 渲染选择 img

render () {
return (
  <div>
    <form onSubmit={this.submitChange}>
      <button onClick={this.submitChange} value='Submit'>Gen</button>
   <div>
       <img src='http://i.imgflip.com/1bij.jpg' onLoad={this.loadImg} />
   </div>
    </form>
  </div>
)}}

【问题讨论】:

  • 问题是什么,请通过示例说明您面临的问题或问题
  • componentDidMount的代码移动/复制到submitChange

标签: javascript html json reactjs api


【解决方案1】:
export class MemeGenerator extends React.Component {
constructor (props) {
super(props)
this.state = {
  apiData: []
}
this.submitChange = this.submitChange.bind(this)
}
componentDidMount () { /* fetch something as default here to show user or nothing till user pushes Gen button*/}

    submitChange (name) {
    fetch(`https://api.imgflip.com/${name}`)
    .then(response => response.json())
    .then(data => {
       this.setState({
       apiData: data
       })
    console.log(this.state.apiData)
    })
    }

render () {
return (
  <div>
    <form onSubmit={this.submitChange}>
      /* you should decide whre to get this name from an array of names from state? hardcode enum ...*/
      <button onClick={this.submitChange({name})} value='Submit'>Gen</button>
   <div>
       <img src='http://i.imgflip.com/1bij.jpg' onLoad={this.loadImg} />
   </div>
    </form>
  </div>
)}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2019-05-19
    • 2014-07-27
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 2013-05-22
    相关资源
    最近更新 更多