首页 > 解决方案 > 如何渲染使用表单输入添加的数据?

问题描述

我正在从 API 呈现信息,但我还需要呈现使用 webform 添加的新信息。我制作了这个表单来添加简单的信息作为来自 API 的对象。如何在此处呈现从此表单添加的数据?

function FormPage({ setData }) {
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [id, setId] = useState(0);

    const handleSubmit = (e) => {
        e.preventDefault();
        const book= { name, description, id}


        fetch('link-from-api', {
            method: 'POST',
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(book)
        }).then(() => {
            console.log('new book added');            
        })
    }

    return (
        <>     
                    <form noValidate autoComplete="off" onSubmit={handleSubmit}>
                            <TextField
                                required
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                label="Name" />
                            <TextField
                                required
                                value={description}
                                onChange={(e) => setDescription(e.target.value)}
                                label="Description" />
                            <button type="submit" onClick={handleId}> set</button> 
                    </form>
        </>
    );
}

export default FormPage;

当我添加一本新书时,我需要在这个文档中看到它:

function BooksPage() {
    const [books, setBooks] = useState([]);

    useEffect(() => {
        fetch('link here')
            .then(res => {
                return res.json();
            })
            .then((data) => {
                setBooks(data)
            })
    }, [])


    return (
        <Container>
            <Header />
            {books && 
            <ListBooks props={books} />}
        </Container>
    )
}

谁能帮我?提前致谢。

标签: javascriptreactjsreact-hooksuse-effect

解决方案


您需要使用lifting the state up这里调用的概念。

books在这两个组件的公共父组件中定义您的状态变量,FormPage然后BooksPage

将此方法传递给组件 FormPage。

const addBook = (book) => {
  setBooks(b => [...b, book])
}

调用此方法

const handleSubmit = (e) => {
    e.preventDefault();
    const book= { name, description, id}


    fetch('link-from-api', {
        method: 'POST',
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(book)
    }).then(() => {
        console.log('new book added');
        addBook(book)          
    })
}

books并传递setBooks到BooksPage 页面。


推荐阅读