【发布时间】:2020-11-08 15:22:15
【问题描述】:
嗨,我是新手,我正在制作一个模因生成器。我试图将它从一个类转换为反应钩子,不知道为什么它不起作用。这是我目前所拥有的,当我尝试生成新图像时出现错误。
import React, { useEffect, useState } from "react"
function MemeGenerator() {
const [newText, setNewText] = useState({
topText: "",
lastName: ""
})
const [randomImg, setrandomImg] = useState("http://i.imgflip.com/1bij.jpg")
const [allMemeImgs, setallMemeImages] = useState([])
useEffect(()=> {
fetch("https://api.imgflip.com/get_memes")
.then(response => response.json())
.then(response => {
const {memes} = response.data
setallMemeImages({allMemeImgs: memes})
})
},[])
function handleChange(event) {
const {name, value} = event.target
setNewText({
...newText,
[name]: value
})
}
// error is on this function I believe
function handleSubmit(event) {
event.preventDefault()
const randNum = Math.floor(Math.random() * allMemeImgs.length)
alert(randNum)
const randMemeImg = allMemeImgs[randNum].url
setrandomImg(randMemeImg)
}
return (
<div>
<form className="meme-form" onSubmit={handleSubmit}>
<input
type="text"
name="topText"
placeholder="Top Text"
value={newText.topText}
onChange={handleChange}
/>
<input
type="text"
name="bottomText"
placeholder="Bottom Text"
value={newText.bottomText}
onChange={handleChange}
/>
<button>Gen</button>
</form>
<div className="meme">
<img src={randomImg} alt="" />
<h2 className="top">{newText.topText}</h2>
<h2 className="bottom">{newText.bottomText}</h2>
</div>
</div>
)
}
我之前的工作是:
import React, {Component} from "react"
class MemeGenerator extends Component {
constructor() {
super()
this.state = {
topText: "",
bottomText: "",
randomImg: "http://i.imgflip.com/1bij.jpg",
allMemeImgs: []
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
componentDidMount() {
fetch("https://api.imgflip.com/get_memes")
.then(response => response.json())
.then(response => {
const {memes} = response.data
this.setState({ allMemeImgs: memes })
})
}
handleChange(event) {
const {name, value} = event.target
this.setState({ [name]: value })
}
handleSubmit(event) {
event.preventDefault()
const randNum = Math.floor(Math.random() * this.state.allMemeImgs.length)
const randMemeImg = this.state.allMemeImgs[randNum].url
this.setState({ randomImg: randMemeImg })
}
render() {
return (
<div>
<form className="meme-form" onSubmit={this.handleSubmit}>
<input
type="text"
name="topText"
placeholder="Top Text"
value={this.state.topText}
onChange={this.handleChange}
/>
<input
type="text"
name="bottomText"
placeholder="Bottom Text"
value={this.state.bottomText}
onChange={this.handleChange}
/>
<button>Gen</button>
</form>
<div className="meme">
<img src={this.state.randomImg} alt="" />
<h2 className="top">{this.state.topText}</h2>
<h2 className="bottom">{this.state.bottomText}</h2>
</div>
</div>
)
}
错误说: TypeError: undefined is not an object (evalating 'allMemeImgs[randNum].url')
【问题讨论】:
-
setallMemeImages({allMemeImgs: memes})应该是setallMemeImages(memes) -
应该是setallMemeImages(memes);
标签: reactjs react-native