当我想将某些内容推送到主页时,我会使用useHistory,但在这种情况下,将useHistory添加到PendulChange会迫使页面在我每次键入内容时都路由到/songs。(因为PendulChange会跟踪表单数据字段中的更改。)
提交表单后如何转到/songs页面?
import "./CreateSong.css";
import { useState } from "react";
import { useHistory } from "react-router-dom";
export default function CreateSong(props) {
const [formData, setFormData] = useState({
artist: "",
title: "",
genre: "",
album: "",
year_released: "",
image_url: "",
});
const history = useHistory();
const { artist, title, genre, album, year_released, image_url } = formData;
const { handleCreate } = props;
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prevState) => ({
...prevState,
[name]: value,
}))
}
//history.push("/songs")
//Find a way to route back to all songs after submitting form
return (
<div className="create-container">
<form
onSubmit={(e) => {
e.preventDefault();
handleCreate(formData);
}}
>
<h1>Tell us about your favorite song here!</h1>
<input
type="text"
name="artist"
value={artist}
placeholder="Artist"
onChange={handleChange}
/>
<input type="text" name="title" value={title} placeholder="Title" onChange={handleChange} />
<input type="text" name="genre" value={genre} placeholder="Genre" onChange={handleChange} />
<input type="text" name="album" value={album} placeholder="Album" onChange={handleChange} />
<input
type="text"
name="year_released"
value={year_released}
placeholder="Year Released"
onChange={handleChange}
/>
<input
type="text"
name="image_url"
value={image_url}
placeholder="Image URL"
onChange={handleChange}
/>
<button>Submit</button>
</form>
</div>
);
}
字符串
1条答案
按热度按时间bogh5gae1#
只需将
history.push("/songs")
移动到onSubmit
内部:字符串