【发布时间】:2020-07-29 22:54:41
【问题描述】:
我正在尝试根据用户输入字段获取 api 数据。如何获取这些数据的值?
我的 api 端点像这样 "http://localhost:8000/api/p_list?search=" 。每当用户输入值时,端点就像这样“http://localhost:8000/api/p_list?search=01”这里是输入字段值是“01”。我想得到结果的值。
我可能是 reactjs 的新手。我在下面尝试了类似的东西,但这是我要获取的静态 API url。我不确定如何根据用户输入字段获取动态 url。
如果有人能帮助我解决我想要解决的问题,那就太好了。非常感谢您。
./src/productList.js
import React, {Component} from "react";
import Contacts from './productListHook.js';
export default class App extends Component{
state = {
contacts: []
}
componentDidMount() {
fetch('http://localhost:8000/api/p_list?search=')
.then(res => res.json())
.then((data) => {
this.setState({ contacts: data })
})
.catch(console.log)
}
render(){
return(
<Contacts contacts={this.state.contacts} />
)
}
}
./src/ProductListHook.js
import React from 'react'
const Contacts = ({ contacts }) => {
return (
<section class="product_list section_padding">
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="product_sidebar">
<div class="single_sedebar">
<form action="#">
<input type="text" name="#" placeholder="Search keyword"/>
<i class="ti-search"></i>
</form>
</div>
</div>
</div>
<div class="col-sm-9">
<div class="product_list">
<div class="row">
{contacts.map((contact) => (
<div class="col-lg-3 col-md-9">
<div class="single_product_item">
<img src={contact.image} alt="" class="img-fluid" />
<h3> <a href={contact.url}>{contact.title}</a> </h3>
<p>From ${contact.price}</p>
</div>
</div>
))}
</div>
<div class="load_more_btn text-center">
<a href="#" class="btn_3">Load More</a>
</div>
</div>
</div>
</div>
</div>
</section>
)
};
export default Contacts
【问题讨论】:
-
您需要将输入值传递给请求 url 吗?
-
您可以创建一个包含用户输入的状态。然后它将被存储并可供您调用。
-
我要解决的这个答案是“therichpost.com/get-input-field-value-button-click-reactjs”吗? @happyZZR1400
-
我可能是 reactjs 的新手,我不知道该怎么做。你能在沙箱环境中运行这段代码吗? @TheoWckr
标签: javascript reactjs react-redux