我有一个反应问题,这让我抓狂

  • 本文关键字:问题 有一个 reactjs
  • 更新时间 :
  • 英文 :


我已经测试了api,它可以工作并显示我希望它如何工作,但问题是,当我试图添加像搜索栏这样简单的东西时,我发现我很挣扎。我正在努力学习反应,并一直很享受,希望有人能指出他们可能看到的任何错误以及我遇到的问题。每当我在搜索栏中输入并提交时,console.log(poke(都会返回两个包含大量信息的对象,而这些信息都不是文本框中的值。任何想法以及任何前进的指南或提示都将受到赞赏。

class Card extends React.Component {
constructor() {
super();
this.state = {
loading: true,
pokemon: null,
inputBox: "",
}
this.componentDidMount = this.componentDidMount.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange({ target }) {
console.log({target})
this.setState({
[target.name]: target.value
});
}
async componentDidMount(poke) 
{
console.log(poke);
const url = `https://pokeapi.co/api/v2/pokemon/${poke}`;
const response = await fetch(url);
const data = await response.json();
this.setState( {pokemon : data, loading : false} )
}

render() {
return (
<article className="pokemonStats"
style={{
position: 'absolute', left: '50%', top: '50%',
transform: 'translate(-50%, -50%)'
}}>
{this.state.loading || !this.state.pokemon  ?( 
<>
<input name="input" 
id="first_name"
type="textbox" 
name="inputBox"
placeholder="Enter pokemon here..."
value={ this.state.inputBox }
onChange={ this.handleChange }/>
<button value="send" onClick={this.componentDidMount}>Search</button>

componentDidMount是一个生命周期方法,在第一次装载后自动运行。所以你不能呼叫this.comopnentDidMount

async setData() 
{
const poke = this.state.inputBox
const url = `https://pokeapi.co/api/v2/pokemon/${poke}`;
const response = await fetch(url);
const data = await response.json();
this.setState( {pokemon : data, loading : false} )
}
<button value="send" onClick={this.setData}>Search</button>

componentDidMount是生命周期方法。如果你是新手,尝试使用功能组件。钩子更容易理解,也更容易操作。您也生成了错误的URL。您在URL字符串中传递点击事件,而URL字符串必须使用inputBox状态进行计算。

import React from "react";
import "./styles.css";
export default function App() {
return (
<div className="App">
<Card />
</div>
);
}
class Card extends React.Component {
constructor() {
super();
this.state = {
loading: true,
pokemon: null,
inputBox: ""
};
this.getPokemon = this.getPokemon.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange({ target }) {
this.setState({
[target.name]: target.value
});
}
async getPokemon(e) {
try {
console.log(this.state.inputBox);
const url = `https://pokeapi.co/api/v2/pokemon/${this.state.inputBox}`;
const response = await fetch(url);
const data = await response.json();
console.log(data);
this.setState({ pokemon: data });
} catch (err) {
console.log(err);
} finally {
this.setState({ loading: false });
}
}
render() {
return (
<article
className="pokemonStats"
style={{
position: "absolute",
left: "50%",
top: "50%",
transform: "translate(-50%, -50%)"
}}
>
{this.state.pokemon && (
<span>{JSON.stringify(this.state.pokemon, null, 4)}</span>
)}
<input
name="inputBox"
id="first_name"
type="textbox"
placeholder="Enter pokemon here..."
value={this.state.inputBox}
onChange={this.handleChange}
/>
<button value="send" onClick={this.getPokemon}>
Search
</button>
</article>
);
}
}

最新更新