ruby-on-rails 提交表单后推到我的/歌曲页面

pu3pd22g  于 4个月前  发布在  Ruby
关注(0)|答案(1)|浏览(67)

当我想将某些内容推送到主页时,我会使用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>
  );
}

字符串

bogh5gae

bogh5gae1#

只需将history.push("/songs")移动到onSubmit内部:

onSubmit={(e) => {
  e.preventDefault();
  handleCreate(formData);
  history.push("/songs")
}}

字符串

相关问题