在 netlify 上部署后 JSON 中 React.js 待办事项应用程序位置 0 中的意外标记 u

Unexpected token u in JSON at position 0 in React.js todo app after deployment on netlify

我正在尝试在 netlify 上部署 React 应用程序。在本地,我的 React Todo 应用程序运行良好,本地存储也在(本地)持久保存数据。但是当我在 netlify 上部署网络应用程序时,在访问实时 link 后,它向我显示了这个错误:“Unexpected token u in JSON at position 0 at JSON.parse” 因为它正在检索不明确的。 我尝试过的解决方案:检查错字 2:检查控制台中正确显示数据的对象。 3:我还在 App() 函数中保留了 getTodoFromLocal 函数并保持了初始状态 const [todos, setTodos] = useState([]); (到空数组)但这不是在页面重新加载时保留数据

我的代码App.js

import React, {useEffect, useState} from 'react';
import './App.css';
import { Header, Form, TodoList } from './components';


// get data from local
const getTodoFromLocal = () => {
  if(localStorage.getItem("todos") === null){
    localStorage.setItem("todos", JSON.stringify([]));
  } else {
      try{
        let localTodo = localStorage.getItem("todos");
        let parsedTodo = JSON.parse(localTodo)
        return parsedTodo; 
      } catch(error) {
        console.log(error);
      }
   }
 }

const App = () => {
  // states
  const [inputText, setInputText] = useState("");
  const [todos, setTodos] = useState(getTodoFromLocal());
  const [status, setStatus] = useState("all");
  const [filteredTodo, setFilteredTodo] = useState([]);

  // run this only once when app loads
  useEffect(() => {
    getTodoFromLocal();
  }, [])

  // Run once when app loads and every time when there is any change in todos ot status
  useEffect(() => {
    filterHandler();
    saveToLocal();
  }, [todos, status])

  // functions
  const filterHandler = () =>{
    switch (status) {
      case 'completed':
       setFilteredTodo(todos.filter(todo => todo.completed === true));
       break;
      case 'incompleted':
        setFilteredTodo(todos.filter(todo => todo.completed === false));
        break;
      default:
        setFilteredTodo(todos);
        break;
    }
  }

  // save to local storage / set todos;
  const saveToLocal = () => {
    localStorage.setItem("todos", JSON.stringify(todos));
  };
  

  return (
    <div className="App">
      <Header />
      <Form inputText = {inputText} 
        setInputText={setInputText} 
        todos={todos}  
        setTodos={setTodos} 
        setStatus={setStatus}
        />
      <TodoList 
        todos={todos} 
        setTodos={setTodos} 
        filteredTodo={filteredTodo}
      />
    </div>
  );
}

export default App;

TodoList.js

import React from 'react';
import TodoItem from './TodoItem';

const TodoList = ({todos, setTodos, filteredTodo}) =>  {
  return (
    <div className='todo-container'>
        <ul className='todo-list'>
          {filteredTodo && filteredTodo.map(todo => (
            <TodoItem 
              key={todo.id} 
              todo={todo} 
              todos={todos} 
              setTodos={setTodos}
              text={todo.text}
              />
          ))}
        </ul>
    </div>
  )
}

export default TodoList;

Form.js

import React from 'react';
import './form.css';
import { v4 as uuidv4 } from 'uuid';


function Form({inputText, setInputText, todos, setTodos, setStatus}) {

  const inputHandler = (e) => {
    setInputText(e.target.value);
  }

  const submitHandler = (e) =>{
    e.preventDefault();
    // generate unique id for todo lists.
    const uniqueId = uuidv4(); 
    //add todo object on click of button
    const addItem = !inputText ? alert("enter somthing")  :  setTodos([
      ...todos, {id: uniqueId, text: inputText, completed: false }
    ]);
 
    //reset the input field after adding todo
    setInputText("");

    return addItem;
  }

  // filtered todo
  const statusTodo = (e) => {
    setStatus(e.target.value);
  }

  return (
    <form>
        <input  type="text" className="todo-input" onChange={inputHandler} value={inputText}/>
        <button className="todo-button" type="submit" onClick={submitHandler}>
            <i className="fas fa-plus-square"></i>
        </button>
        <div className="select">
          <select onChange={statusTodo} name="todos" className="filter-todo">
              <option value="all">All</option>
              <option value="completed">Completed</option>
              <option value="incompleted">Incompleted</option>
          </select>
          <span><i className="fas fa-chevron-down"></i></span>
        </div>
  </form>
  )
}

export default Form;

TodoItem.js

import React from 'react';
import './todo.css';

const TodoItem = ({text, todo, todos, setTodos}) => {
  //delete an item;
  const deleteHandler = () => {
    setTodos(todos.filter(el => el.id !== todo.id))
  }

  const completeHandler = () => {
    setTodos(todos.map((item )=> {
      if(item.id === todo.id){
        return {
          ...item, completed: !todo.completed
        }
      }
      return item;
    }));
  }

  return (
    <div className='todo'>
        <li className={`todo-item ${todo.completed ? 'completed' : "" }`}>{text}</li>
        <button className='complete-btn' onClick={completeHandler}>
            <i className='fas fa-check'></i>
        </button> 
        <button className='trash-btn' onClick={deleteHandler}>
            <i className='fas fa-trash'></i>
        </button> 
    </div>
  )
}

export default TodoItem;

直播link:https://clinquant-parfait-ceab31.netlify.app/

Github link: https://github.com/Mehreen57/Todo-app-react

我希望我已经解释了这个问题。我将感谢所有能在这方面帮助我的人。

提前谢谢你。

我发现了错误。一步一步来。

  1. 你有 getTodoFromLocal 当你在这里设置 Todos const [todos, setTodos] = useState(getTodoFromLocal()); 时调用它。

  2. 由于 localStorage.getItem("todos") 为空,您将 todos 设置为 [] 但不要 return 任何 return 未定义且todos 的值 更改为 undefined.

  3. 然后你有函数 saveToLocal,你将 todos 存储在 localStorage 中。只要待办事项发生变化,它就会在 useEffect 中调用。

  4. Todos 更改为 undefined > 调用 useEffect > 在 saveToLocal 函数中 todos(undefined) 存储在 localStorage.

更新代码:

if (localStorage.getItem("todos") === null) {
    localStorage.setItem("todos", JSON.stringify([]));
    return []
  }