【发布时间】:2020-10-31 02:12:03
【问题描述】:
我正在开发一个 API 应用程序,该应用程序将在用户输入职位描述或位置时返回一个职位列表。最初,页面将返回所有作业并在第一次渲染时将它们显示到屏幕上(默认使用效果)。现在我希望当用户单击按钮时,页面将根据用户的输入呈现作业列表。如何在我的 onSubmit 函数上执行此操作以更新 useEffect 挂钩的值?
import React, { useState, useEffect} from 'react';
import SearchForm from './componenets/Form.js';
import JobLists from './componenets/JobLists'
import axios from 'axios'
function App() {
const [posts, setPosts] = useState([]) //posts store a list of jobs
const [description, setDescription] = useState('') //description of the job (user's input)
const [location, setLocation] = useState('') //location of the job (user's input)
//description input handle
const handleDescriptionChange = (e) => {
setDescription(e.target.value);
}
//location input handle
const handleLocationChange = (e) => {
setLocation(e.target.value);
}
//submit button handle
const onSubmit = e => {
e.preventDefault();
//once the user enter input and clicks on button, update the the useEffect hooks
}
//get data from github job API (fetching by description and location)
const url = `https://cors-anywhere.herokuapp.com/https://jobs.github.com/positions.json?description=${description}&location=${location}`
useEffect(() => {
axios.get(url)
.then(res =>{
console.log(res)
setPosts(res.data)
})
.catch(err =>{
console.log(err)
})
}, [])
return (
<div>
<SearchForm
description={description}
handleDescriptionChange={handleDescriptionChange}
location={location}
handleLocationChange={handleLocationChange}
onSubmit={onSubmit} />
{
posts.map((job) => <JobLists job={job} key={job.id} />) //map through each job
}
</div>
)
}
export default App;
【问题讨论】:
标签: reactjs react-hooks use-effect buttonclick