尝试绑定提交并保存到localStorage

问题描述 投票:0回答:2

在我的 App.js 代码中,我尝试绑定并捕获“handlesubmit”函数,然后附加到将填充的空列表。谢谢。

import React from 'react';

const App = () => {
  const [songs, setSongs] = React.useState([]);

  React.useEffect(() => {
    const data = localStorage.getItem('songs');
    if (!data) { }
    setSongs(JSON.parse(data));
  }, []);

  React.useEffect(() => {
    localStorage.setItem('songs', JSON.stringify(songs));
  });

  const handleSubmit = data => {
    setSongs([data]);
  }

  return (
    <main>
    <h1>Music Editor</h1>

    <form onSubmit={this.props.handleSubmit(this.handleSubmit.bind(this))} autoComplete="false">
      <label for="title">Title:</label>
      <input type="text" id="title" name="title" placeholder="Type title/name of song" value="" />
      <input type="submit" value="Add song" />
    </form>

    </main>
  );
}

export default App;
reactjs
2个回答
1
投票

解释已在代码本身中注释。 这是 codesandbox 链接,可以查看该应用程序的工作情况。

import React from 'react';

const App = () => {
  const [songs, setSongs] = React.useState([]);

  // use another state for song title
  const [songTitle, setSongTitle] = React.useState('');

  React.useEffect(() => {
    const data = localStorage.getItem('songs');
    // only update the state when the data persists
    if (data) setSongs(JSON.parse(data));
  }, []);

  // update the localStorage whenever the songs array changes
  React.useEffect(() => {
    localStorage.setItem('songs', JSON.stringify(songs));
  }, [songs]);

  // inside the functional component, there is no "this" keyword
  const handleSubmit = (event) => {
    event.preventDefault();
    // append the new song title with the old one
    setSongs([
      ...songs,
      songTitle
    ]);
  }

  return (
    <main>
    <h1>Music Editor</h1>

    <form onSubmit={handleSubmit} autoComplete="false">
      <label htmlFor="title">Title:</label>
      <input 
        type="text" 
        id="title" 
        name="title" 
        placeholder="Type title/name of song" 
        value={songTitle}
        onChange={e => setSongTitle(e.target.value)}
      />
      <input type="submit" value="Add song" />
    </form>

    </main>
  );
}

export default App;

0
投票
// heres example how you can handlesubmit in form using local storage

 const handleSubmit = (e) => {
        e.preventDefault();
        // Simulate user login
        const su = localStorage.getItem('user');
        if (su) {
          const user = JSON.parse(storedUser);
          if (user.email === fd.email) {
            setUser(user);
            navigate('/profile');
          } else {
            setError('Invalid credentials');
          }
        } else {
          setError('User not found');
        }
      };
© www.soinside.com 2019 - 2024. All rights reserved.