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

isc*_*eam 8 reactjs axios react-hooks

我正在尝试根据表单提交在功能组件内进行 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>
    )
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试这样做时,会出现以下错误:

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
Run Code Online (Sandbox Code Playgroud)

我如何执行此操作?

Ker*_*tam 13

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

文档

仅从 React 函数调用 Hook 不要从常规 JavaScript 函数调用 Hook。相反,您可以:

? 从 React 函数组件调用 Hook。

? 从自定义 Hooks 调用 Hooks(我们将在下一页了解它们)。通过遵循此规则,您可以确保组件中的所有有状态逻辑在其源代码中都清晰可见。

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

  useEffect(() => {
    fetchData()
  }, [])
Run Code Online (Sandbox Code Playgroud)

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

const handleSubmit = e => {
    e.preventDefault()
    fetchData()
  }
Run Code Online (Sandbox Code Playgroud)

所以整个代码看起来像:

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>
  )
}

Run Code Online (Sandbox Code Playgroud)

  • 由于我希望在表单提交后进行调用,所以我不应该要求 useEffect 吗? (4认同)
  • @iscream 是的(抱歉,回复晚了) (2认同)