第1期-通过在输入字段中添加value
个属性来解决
第一个组件应在提交时清空三个输入字段。 状态已正确更改,但屏幕上没有任何变化-标题,作者和url已被正确清空,但先前的文本值保持可见,并且组件未重新呈现:
import React, { useState } from 'react'
import blogService from '../services/blogs'
const CreateBlog = props => {
const [title, setTitle] = useState('')
const [author, setAuthor] = useState('')
const [url, setUrl] = useState('')
async function handleCreate(event) {
event.preventDefault()
try {
const blog = { title, author, url }
await blogService.create(blog, props.token)
props.changeblogAdded()
setTitle('')
setAuthor('')
setUrl('')
} catch(error) { console.log(error) }
}
return (
<form id="new-blog-form" onSubmit={handleCreate}>
<h2>Create new blog</h2>
{`title `}<input type="text" required onChange={event => setTitle(event.target.value)}></input>
<br></br>
{`author `}<input type="text" required onChange={event => setAuthor(event.target.value)}></input>
<br></br>
{`url `}<input type="url" required onChange={event => setUrl(event.target.value)}></input>
<br></br>
<button type="submit">create</button>
</form>
)
}
export default CreateBlog
第2期问题
子组件中的props.changeblogAdded()
调用应该可以更改父App组件的状态,并且可以成功更改,但是父组件也不会重新呈现:
import React, { useState } from 'react';
import Blogs from './components/Blogs'
import Login from './components/Login';
import CreateBlog from './components/CreateBlog'
function App() {
const [token, setToken] = useState('')
const [blogAdded, setBlogAdded] = useState(false)
function changeblogAdded() {
setBlogAdded(!blogAdded)
}
function displayBlogs() {
return (token ? <Blogs></Blogs> : '')
}
function newBlogForm() {
return (token ? <CreateBlog token={token} changeblogAdded={changeblogAdded}></CreateBlog> : '')
}
console.log(blogAdded);
return (
<div className="App">
<Login setToken={setToken}></Login>
{displayBlogs()}
{newBlogForm()}
</div>
);
}
export default App;
如何设置CreateBlog和App组件以正确地重新呈现?