我在点击我的React应用程序上的删除图标时遇到了此错误。

huangapple go评论71阅读模式
英文:

I got this error when hit the delete icon on my react app

问题

无法读取未定义的属性(读取'_id')TypeError: 无法读取未定义的属性(读取'_id')

这是我的App.js文件

function App() {
	const [todos, setTodos] = useState([]);
	const [popupActive, setPopupActive] = useState(false);
	const [newTodo, setNewTodo] = useState("");

	useEffect(() => {
		GetTodos();
	}, []);

	const GetTodos = () => {
		fetch(api_base + '/todos')
			.then(res => res.json())
			.then(data => setTodos(data))
			.catch((err) => console.error("错误:", err));
	}

	const completeTodo = async id => {
		const data = await fetch(api_base + '/todo/complete/' + id).then(res => res.json());

		setTodos(todos => todos.map(todo => {
			if (todo._id === data._id) {
				todo.complete = data.complete;
			}

			return todo;
		}));
		
	}

	const deleteTodo = async id => {
		const data = await fetch(api_base + '/todo/delete/' + id, { method: "DELETE" }).then(res => res.json());

		setTodos(todos => todos.filter(todo => todo._id !== data.result._id));
	}
}

请注意,我已将HTML转义字符(如")替换为正常的双引号。

英文:

Cannot read properties of undefined (reading '_id') TypeError: Cannot read properties of undefined (reading '_id')

this is my App.js file

function App() {
	const [todos, setTodos] = useState([]);
	const [popupActive, setPopupActive] = useState(false);
	const [newTodo, setNewTodo] = useState("");

	useEffect(() => {
		GetTodos();
	}, []);

	const GetTodos = () => {
		fetch(api_base + '/todos')
			.then(res => res.json())
			.then(data => setTodos(data))
			.catch((err) => console.error("Error: ", err));
	}

	const completeTodo = async id => {
		const data = await fetch(api_base + '/todo/complete/' + id).then(res => res.json());

		setTodos(todos => todos.map(todo => {
			if (todo._id === data._id) {
				todo.complete = data.complete;
			}

			return todo;
		}));
		
	}

	const deleteTodo = async id => {
		const data = await fetch(api_base + '/todo/delete/' + id, { method: "DELETE" }).then(res => res.json());

		setTodos(todos => todos.filter(todo => todo._id !== data.result._id));
	}

答案1

得分: 0

那是因为数据可能在那里变成了未定义的,请尝试添加一个条件来检查数据是否存在,这实际上是类型错误,你可以通过检查data及其属性是否存在来修复这个错误,然后继续进行处理,这样可以防止类型错误。


function App() {
    const [todos, setTodos] = useState([]);
    const [popupActive, setPopupActive] = useState(false);
    const [newTodo, setNewTodo] = useState("");

    useEffect(() => {
        GetTodos();
    }, []);

    const GetTodos = () => {
        fetch(api_base + '/todos')
            .then(res => res.json())
            .then(data => setTodos(data))
            .catch((err) => console.error("Error: ", err));
    }

    const completeTodo = async id => {
        const data = await fetch(api_base + '/todo/complete/' + id).then(res => res.json());
        if (data && data._id) {
            setTodos(todos => todos.map(todo => {
                if (todo._id === data._id) {
                    todo.complete = data.complete;
                }

                return todo;
            }));
        }
    }

    const deleteTodo = async id => {
        const data = await fetch(api_base + '/todo/delete/' + id, { method: "DELETE" }).then(res => res.json());
        if (data && data.result && data.result._id) {
            setTodos(todos => todos.filter(todo => todo._id !== data.result._id));
        }
    }
}

该函数只会在数据存在时触发,因此您不会收到任何未定义错误,请尝试复制粘贴这个,希望能解决问题!

英文:

That is because the data must be getting undefined there, try to add a condition to check if data is present ,this is actually type error and you can fix this by checking if data and its properties are present continue with process this will prevent type errors


function App() {
    const [todos, setTodos] = useState([]);
    const [popupActive, setPopupActive] = useState(false);
    const [newTodo, setNewTodo] = useState("");

    useEffect(() => {
        GetTodos();
    }, []);

    const GetTodos = () => {
        fetch(api_base + '/todos')
            .then(res => res.json())
            .then(data => setTodos(data))
            .catch((err) => console.error("Error: ", err));
    }

    const completeTodo = async id => {
        const data = await fetch(api_base + '/todo/complete/' + id).then(res => res.json());
if (data && data._id) {
        setTodos(todos => todos.map(todo => {
            if (todo._id === data._id) {
                todo.complete = data.complete;
            }

            return todo;
        }));
}
        
    }

    const deleteTodo = async id => {
        const data = await fetch(api_base + '/todo/delete/' + id, { method: "DELETE" }).then(res => res.json());
if (data && data.result && data.result._id) {
        setTodos(todos => todos.filter(todo => todo._id !== data.result._id));
}
    }

the function will trigger only if the data is present so you won't get any undefined error, copy paste this and try.I hope it works!!

答案2

得分: 0

你应该检查 data 响应内的 result 键。你可以查看下面的代码来验证 result 键:

const data = await fetch(api_base + '/todo/delete/' + id, { method: "DELETE" }).then(res => res.json());
if (data && data?.result?.__id) {
    setTodos(todos => todos.filter(todo => todo._id !== data.result._id))
}
英文:

You should have check the result key inside data response. You can check the below code for result key validation

const data = await fetch(api_base + '/todo/delete/' + id, { method: "DELETE" }).then(res => res.json());
if (data && data?.result?.__id) {
    setTodos(todos => todos.filter(todo => todo._id !== data.result._id))
}

huangapple
  • 本文由 发表于 2023年6月9日 13:38:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定