我正在尝试通过相同的表单添加和编辑记录。它工作正常,但是当我刷新页面时进行编辑时,输入值被擦除。 正如我所注意到的,组件在存储值之前正在渲染,并且 useState 立即运行, 请指导这样做...
编辑链接.js
const EditLink = () => {
const { id } = useParams()
const { links, dispatch } = useContext(LinksContext)
const link = links.find((link) => link.id === id)
const addLink = (updates) => {
database.ref(`links/${id}`)
.set(updates)
.then(() => {
dispatch({
type: "EDIT_LINK",
id,
updates
})
history.push("/dashboard")
})
.catch((e) => {
console.log("Link editing failed", e)
})
}
const removeLink = () => {
database.ref(`links/${id}`)
.remove()
.then(() => {
dispatch({
type: "REMOVE_LINK",
id
})
history.push("/dashboard")
})
}
return (
<>
<Container>
<Alert variant="primary">
<h6 className="mb-0">Edit Link</h6>
</Alert>
</Container>
<LinkForm link={link} addLink={addLink} removeLink={removeLink} />
</>
)
}
链接表单.js
export const LinkForm = ({ link, addLink, removeLink }) => {
const [title, setTitle] = useState(!!link ? link.title : "")
const [description, setDescription] = useState(!!link ? link.description : "")
const [url, setUrl] = useState(!!link ? link.url : "")
const [tags, setTags] = useState(!!link ? link.tags : "")
const [error, setError] = useState('')
const onSubmit = (e) => {
e.preventDefault()
if (!title || !url) {
setError("Title and Url is compulsary")
} else {
const link = { title, url, description, tags }
addLink(link)
}
}
return (
<Container>
<Row className="justify-content-md-center">
<Col md={6}>
{
error.length > 0 &&
<Alert variant="warning">
{error}
</Alert>
}
<Form onSubmit={onSubmit} >
<Form.Group >
<Form.Control
type="text"
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Title"
/>
</Form.Group>
<Form.Group >
<Form.Control
type="text"
id="url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="URL"
/>
</Form.Group>
<Form.Group >
<Form.Control
as="textarea"
rows="2"
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Description"
/>
</Form.Group>
<Form.Group >
<Form.Control
as="textarea"
rows="2"
id="tags"
value={tags}
onChange={(e) => setTags(e.target.value)}
placeholder="Tags"
/>
</Form.Group>
<Form.Group as={Row}>
<Col sm={6} className="mb-1">
<Button variant="info" className="w-100" type="submit">Add </Button>
</Col>
{!!link &&
<Col sm={6}>
<Button
id="removeExpanse"
variant="danger"
className="w-100"
onClick={removeLink}
>Remove </Button>
</Col>}
</Form.Group>
</Form>
</Col>
</Row>
</Container>
)
}
请指导我们..
它工作正常,但是当我刷新页面时进行编辑时,输入值被擦除。
为什么你期望相反的情况发生?刷新页面时,您将重新启动应用程序。在页面重新加载后持久化数据的方法是使用浏览器的localStorage
。