[英]Passing data to another component in React
In my code I have it so the user can search for the type of Pokémon they want and when the user submits it, I want to send it to another component to display all the information.在我的代码中,我有它,因此用户可以搜索他们想要的神奇宝贝类型,当用户提交它时,我想将它发送到另一个组件以显示所有信息。 The issue is the data isn't passing through to the other component I'm pretty new to react so I might be missing something obvious.
问题是数据没有传递到其他组件,我对反应还很陌生,所以我可能会遗漏一些明显的东西。 This is the component that retrieves the data from the api.
这是从 api 检索数据的组件。
const Search = () => {
const [inputValue, setInputValue] = useState("");
const [userData, setUserData] = useState([]);
const userInput = (e) => {
setInputValue(e.target.value);
};
const handleClick = (e) => {
e.preventDefault();
apiCall(inputValue);
};
const apiCall = async (name) => {
const url = `https://pokeapi.co/api/v2/pokemon/${name}`;
const response = await fetch(url);
const data = await response.json();
setUserData(data);
};
return (
<div>
<button className="btn" onClick={handleClick}>
Search
</button>
<input
type="search"
onChange={userInput}
value={inputValue}
placeholder="Enter your pokemon name"
className="btn-search"
></input>
<div>
<PokiApi props={userData} />
</div>
</div>
);
};
This is the component that I want to display the api data to the page.这是我想在页面上显示 api 数据的组件。
export default class PokiApi extends React.Component {
constructor(props) {
super(props);
this.state = {
data: props.props,
};
}
render() {
return (
<div>
<div>
<div>{this.state.data}</div>
</div>
</div>
);
}
}
Try this:尝试这个:
const PokiApi({props}) {
return (
<div>
<div>
<div>{props}</div>
</div>
</div>
);
}
the props in the function component will be userData and props.props is undefined function 组件中的道具将是 userData 并且 props.props 未定义
This
is what you need This
就是你需要的
const Search = () => {
const [inputValue, setInputValue] = useState('');
const [userData, setUserData] = useState();
const userInput = (e) => {
setInputValue(e.target.value);
};
const apiCall = async (name) => {
const url = `https://pokeapi.co/api/v2/pokemon/${name}`;
const response = await fetch(url);
const data = await response.json();
setUserData(data);
};
const handleSubmit = (e) => {
e.preventDefault();
apiCall(inputValue);
};
return (
<div>
<form action='' onSubmit={handleSubmit}>
<button className='btn'>Search</button>
<input type='search' onChange={userInput} value={inputValue} placeholder='Enter your pokemon name' className='btn-search' />
</form>
<div>
<PokiApi data={userData} />
</div>
</div>
);
};
const PokiApi = ({ data }) => {
// data is an array
if (!data) {
return <div>Enter pokemon to get the data</div>;
}
return (
<div>
<h1>{data.name}</h1>
</div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.