gpt4 book ai didi

reactjs - 如何在 React 中基于表单提交应用 useEffect?

转载 作者:行者123 更新时间:2023-12-03 15:54:37 25 4
gpt4 key购买 nike

我正在尝试根据表单提交在功能组件内进行 API 调用:

const SearchForm = () => {
const [keywords, setKeywords] = useState('')
const [fetchedData, setFetchedData] = useState('')

const handleSubmit = (e) => {
e.preventDefault();
useEffect(() => {
async function fetchData() {
const {data} = await axios.post('http://127.0.0.1:8000/api/posts/', keywords)
setFetchedData(data);
}
fetchData()
})
}

return (
<div>
<form onSubmit={ handleSubmit }>
<div className='input-field'>
<input placeholder="Search whatever you wish"
type="text"
value={keywords}
onChange={(e) => setKeywords(e.target.value)}
/>
</div>
</form>
</div>
)
}

但是,当我尝试这样做时,会出现以下错误:
React Hook "useEffect" is called in function "handleSubmit" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

我如何执行此操作?

最佳答案

因为它不是 useEffect 怎么用的。您也不需要在处理程序中调用它。

来自 documentation :

Only Call Hooks from React Functions Don’t call Hooks from regular JavaScript functions. Instead, you can:

✅ Call Hooks from React function components.

✅ Call Hooks from custom Hooks (we’ll learn about them on the next page). By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code.



如果你想在你的功能组件上获取数据,你可以像这样使用 useEffect :

  useEffect(() => {
fetchData()
}, [])

并且您希望通过单击按钮触发 fetch 调用:

const handleSubmit = e => {
e.preventDefault()
fetchData()
}

所以整个代码看起来像:

const SearchForm = () => {
const [keywords, setKeywords] = useState('')
const [fetchedData, setFetchedData] = useState('')

async function fetchData() {
const { data } = await axios.post(
'http://127.0.0.1:8000/api/posts/',
keywords
)
setFetchedData(data)
}

useEffect(() => {
fetchData()
}, [])

const handleSubmit = e => {
e.preventDefault()
fetchData()
}

return (
<div>
<form onSubmit={handleSubmit}>
<div className="input-field">
<input
placeholder="Search whatever you wish"
type="text"
value={keywords}
onChange={e => setKeywords(e.target.value)}
/>
</div>
</form>
</div>
)
}

关于reactjs - 如何在 React 中基于表单提交应用 useEffect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62248741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com