[英]How to store a string from input tag in a variable using react?
I'm a beginner react js user and I want to store a string from input tag in a variable.我是一个初学者反应 js 用户,我想将输入标签中的字符串存储在变量中。 Then I want the string stored in the variable to be connected with API URL as shown below
然后我希望存储在变量中的字符串与 API URL 连接,如下所示
` `
const [stats, setStats] = useState([]);
const ID="";
useEffect(() => {
axios
.get(`https://fortnite-api.com/v2/stats/br/v2/${ID}`)
.then(res => {
setStats(res.data);
console.log(res.data);
})
.catch(error => console.log(error));
}, []);
return (
<div>
<h1>Search a Player</h1>
<form>
<input
type='text'
//onChange={}
placeholder='Search'
/>
</form>
</div>
)
Your help will make my day.你的帮助会让我开心。
You will have to save your ID
as a state variable.您必须将
ID
保存为状态变量。 You can thencontrol its value based on your onChange
event handler.然后,您可以根据
onChange
事件处理程序控制其值。
const [stats, setStats] = useState([]);
const [ID,setID] = useState('');
const changeId = (event) =>{
setID(event.target.value);
}
useEffect(() => {
if(ID!='') {
axios
.get(`https://fortnite-api.com/v2/stats/br/v2/${ID}`)
.then(res => {
setStats(res.data);
console.log(res.data);
})
.catch(error => console.log(error));
}
}, [ID]);
return (
<div>
<h1>Search a Player</h1>
<form>
<input
type='text'
onChange={(event) => {changeId(event.target.value) }
placeholder='Search'
/>
</form>
</div>
)
Ensure, that your useEffect
callback is only called when ID changes.确保您的
useEffect
回调仅在 ID 更改时调用。 So pass in ID
in the dependency array .所以在依赖数组中传入
ID
。 With an empty array it is called only once after component has mounted.对于空数组,它仅在组件安装后调用一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.