与之前的渲染相比,渲染了更多的钩子。使用 React Hooks 发布表单数据时

2023-12-24

今天遇到了hooks的问题。我知道有一个类似的帖子,并且我阅读了使用钩子的规则。现在,当我发布表格时,它给了我这个错误。我知道那是因为我的钩子位于 if 语句内。但我怎样才能把它弄出来呢?如果这个钩子不在函数或语句中,我不知道如何使用它。任何建议将不胜感激。这是代码:

import React, { FunctionComponent, useState, useEffect } from 'react';
import usePost from '../hooks/usepost'
import Article from './article';

interface ArticlePosted {
    title: string,
    body: string,
    author: string
}
const Post: FunctionComponent = () => {

    const [details, detailsReady] = useState({})
    const postArticle = (e) => {
        e.preventDefault()
        const postDetails = {
            title: e.target.title.value,
            body: e.target.body.value,
            author: e.target.author.value
        }
        detailsReady(postDetails)
    }

    if (Object.keys(details).length !== 0) {
        console.log(details)
        usePost('http://localhost:4000/kb/add', details)
    }
    return (
        <div>
            <form onSubmit={postArticle}>
                <p>
                    Title <input type='text' name='title' />
                </p>
                <p>
                    Body <textarea name='body' rows={4} />
                </p>
                <p>
                    Author <input type='text' name='author' />
                </p>
                <button type='submit'>Submit Article</button>

            </form>
        </div>
    );
};

export default Post;

定制挂钩:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const usePost = (url, postDetails) => {
    //set empty object as data
    console.log(url, "DFLSKDJFSDLKFJDLKJFDLFJ")

    console.log(postDetails)
    useEffect(() => {
        console.log('usePost running')
        axios.post(url, postDetails)
            .then(res => {
                console.log(res)
                return
            })
    }
        , [postDetails]);

};

export default usePost

您可以将 if 语句逻辑移至usePost hook.

const usePost = (url, postDetails) => {
    useEffect(() => {
        if (Object.keys(postDetails).length === 0){
            return console.log('Not posting'); // Don't post anything if no details
        }
        // Otherwise, post away
        console.log('usePost running')
        axios.post(url, postDetails)
            .then(res => {
                console.log(res)
                return
            })
    }
        , [postDetails]);

};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

与之前的渲染相比,渲染了更多的钩子。使用 React Hooks 发布表单数据时 的相关文章

随机推荐