#reactjs #react-hooks #use-effect #buttonclick
#reactjs #реагирующие крючки #use-effect #buttonclick
Вопрос:
Я работаю над приложением 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}amp;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;
Ответ №1:
https://codesandbox.io/s/react-form-example-gm9o6
import React, { useState, useEffect } from 'react'
import SearchForm from './componenets/Form.js'
import JobLists from './componenets/JobLists'
import axios from 'axios'
const 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)
const url = `https://cors-anywhere.herokuapp.com/https://jobs.github.com/positions.json?description=${description}amp;location=${location}`
const getPosts = async () => {
await axios
.get(url)
.then((res) => {
console.log(res)
setPosts(res.data)
})
.catch((err) => {
console.log(err)
})
}
//get data from github job API (fetching by description and location)
useEffect(() => {
getPosts()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
//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
getPosts()
}
return (
<div>
<SearchForm
description={description}
handleDescriptionChange={handleDescriptionChange}
location={location}
handleLocationChange={handleLocationChange}
onSubmit={onSubmit}
/>
{
!!posts?.length amp;amp;
posts.map((job) => <JobLists key={job.id} job={job} />) //map through each job
}
</div>
)
}
export default App