无法解决的 create-react-app 错误:未捕获的类型错误:无法读取未定义的属性(读取‘路径名’)
我尝试了互联网上可用的所有解决方案,但还是无法解决这些错误。请帮助我。 遇到类似以下错误:
-
警告:列表中的每个子项都应具有唯一的“key”属性。
检查
Home
的渲染方法。有关更多信息,请参阅 https://reactjs.org/link/warning-keys 。 在 tr 在 Home (http://localhost:3000/static/js/bundle.js:679:75) 在 Routes (http://localhost:3000/static/js/bundle.js:43822:5) 在 div 在 Router (http://localhost:3000/static/js/bundle.js:43755:15) 在 BrowserRouter (http://localhost:3000/static/js/bundle.js:42564:5) 在 App -
未捕获 TypeError:无法读取未定义的属性(读取“pathname”)
在 resolveTo (router.ts:549:1) 在 hooks.tsx:252:1 在 mountMemo (react-dom.development.js:17225:1) 在 Object.useMemo (react-dom.development.js:17670:1) at useMemo (react.development.js:1650:1) at useResolvedPath (hooks.tsx:252:1) at useHref (hooks.tsx:40:1) at LinkWithRef (index.tsx:267:1) at renderWithHooks (react-dom.development.js:16305:1) at updateForwardRef (react-dom.development.js:19226:1)
-
上述错误发生在组件中:at LinkWithRef (http://localhost:3000/static/js/bundle.js:42666:5) at td at tr at tbody at table at div at div at Home (http://localhost:3000/static/js/bundle.js:679:75) 在 Routes 处(http://localhost:3000/static/js/bundle.js:43822:5) 在 div 处 在 Router 处(http://localhost:3000/static/js/bundle.js:43755:15) 在 BrowserRouter 处(http://localhost:3000/static/js/bundle.js:42564:5) 在 App 处
-
未捕获的 TypeError:无法读取未定义的属性(读取“pathname”)
在 resolveTo 处(router.ts:549:1) 在 hooks.tsx:252:1 在 mountMemo 处(react-dom.development.js:17225:1) 在 Object.useMemo 处(react-dom.development.js:17670:1) 在 useMemo (react.development.js:1650:1) 在 useResolvedPath (hooks.tsx:252:1) 在 useHref (hooks.tsx:40:1) 在 LinkWithRef (index.tsx:267:1) 在 renderWithHooks (react-dom.development.js:16305:1) 在 updateForwardRef (react-dom.development.js:19226:1)
-
未捕获的 TypeError:无法读取未定义的属性(读取“pathname”)
在 resolveTo (router.ts:549:1) 在 hooks.tsx:252:1 在 mountMemo (react-dom.development.js:17225:1) 在Object.useMemo (react-dom.development.js:17670:1) at useMemo (react.development.js:1650:1) at useResolvedPath (hooks.tsx:252:1) at useHref (hooks.tsx:40:1) at LinkWithRef (index.tsx:267:1) at renderWithHooks (react-dom.development.js:16305:1) at updateForwardRef (react-dom.development.js:19226:1)
以下是我的代码:
App.js:
import "../node_modules/bootstrap/dist/css/bootstrap.css";
import Navbar from "./component/layout/Navbar";
import About from "./component/pages/About";
import Contact from "./component/pages/Contact";
import Home from "./component/pages/Home";
import NotFound from "./component/pages/NotFound";
import React from "react";
import "./App.css";
import AddUser from "./component/users/AddUser";
import EditUser from "./component/users/EditUser";
import User from "./component/users/User";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
function App(props) {
return (
<Router>
<div className="App">
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/users/add" element={<AddUser />} />
<Route path="/users/edit/:id" element={<EditUser />} />
<Route path="/users/:id" element={<User />} />
<Route path="*" element={<NotFound />} />
</Routes>
</div>
</Router>
);
}
export default App;
Home.js:
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
const Home = () => {
const [users, setUser] = useState([]);
useEffect(() => {
loadUsers();
}, []);
const loadUsers = async () => {
const result = await axios.get("http://localhost:3001/users");
setUser(result.data.reverse());
};
const deleteUser = async (id) => {
await axios.delete(`http://localhost:3001/users/${id}`);
loadUsers();
};
return (
<div className="container">
<div className="py-4">
<h1>Home Page</h1>
<table className="table border shadow">
<thead className="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">User Name</th>
<th scope="col">Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr>
<th scope="row">{index + 1}</th>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
<td>
<Link
className="btn btn-primary mr-2"
to={`/users/${user.id}`}
>
View
</Link>
<Link
className="btn btn-outline-primary mr-2"
to={`/users/edit/${user.id}`}
>
Edit
</Link>
<Link
className="btn btn-danger"
onClick={() => deleteUser(user.id)}
>
Delete
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
};
export default Home;
About.js:
import React from "react";
const About = () => {
return (
<div className="container">
<div className="py-4">
<h1>About Page</h1>
<p className="lead">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque rerum
hic ab veniam reiciendis cum repudiandae, voluptate explicabo nesciunt
nam accusantium? Soluta cupiditate, accusamus commodi praesentium
laborum dolorum libero maiores!
</p>
<p className="lead">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque rerum
hic ab veniam reiciendis cum repudiandae, voluptate explicabo nesciunt
nam accusantium? Soluta cupiditate, accusamus commodi praesentium
laborum dolorum libero maiores!
</p>
<p className="lead">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Cumque rerum
hic ab veniam reiciendis cum repudiandae, voluptate explicabo nesciunt
nam accusantium? Soluta cupiditate, accusamus commodi praesentium
laborum dolorum libero maiores!
</p>
</div>
</div>
);
};
export default About;
Contact.js:
import React from "react";
const Contact = () => {
return (
<div className="container">
<div className="py-4">
<h1>Contact Page</h1>
<form>
<div className="form-group">
<label for="exampleInputEmail1">Email address</label>
<input
type="email"
className="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"
/>
<small id="emailHelp" className="form-text text-muted">
We'll never share your email with anyone else.
</small>
</div>
<div className="form-group">
<label for="exampleInputPassword1">Password</label>
<input
type="password"
className="form-control"
id="exampleInputPassword1"
/>
</div>
<div className="form-group form-check">
<input
type="checkbox"
className="form-check-input"
id="exampleCheck1"
/>
<label className="form-check-label" for="exampleCheck1">
Check me out
</label>
</div>
<button type="submit" className="btn btn-primary">
Submit
</button>
</form>
</div>
</div>
);
};
export default Contact;
User.js:
import React, { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";
const User = () => {
const [user, setUser] = useState({
name: "",
username: "",
email: "",
phone: "",
webiste: "",
});
const { id } = useParams();
useEffect(() => {
loadUser();
}, []);
const loadUser = async () => {
const res = await axios.get(`http://localhost:3001/users/${id}`);
setUser(res.data);
};
return (
<div className="container py-4">
<Link className="btn btn-primary" to="/">
back to Home
</Link>
<h1 className="display-4">User Id: {id}</h1>
<hr />
<ul className="list-group w-50">
<li className="list-group-item">name: {user.name}</li>
<li className="list-group-item">user name: {user.username}</li>
<li className="list-group-item">email: {user.email}</li>
<li className="list-group-item">phone: {user.phone}</li>
<li className="list-group-item">website: {user.website}</li>
</ul>
</div>
);
};
export default User;
EditUser.js:
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useNavigate, useParams } from "react-router-dom";
const EditUser = () => {
let history = useNavigate();
const { id } = useParams();
const [user, setUser] = useState({
name: "",
username: "",
email: "",
phone: "",
website: "",
});
const { name, username, email, phone, website } = user;
const onInputChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
useEffect(() => {
loadUser();
}, []);
const onSubmit = async (e) => {
e.preventDefault();
await axios.put(`http://localhost:3001/users/${id}`, user);
history.push("/");
};
const loadUser = async () => {
const result = await axios.get(`http://localhost:3001/users/${id}`);
setUser(result.data);
};
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h2 className="text-center mb-4">Edit A User</h2>
<form onSubmit={(e) => onSubmit(e)}>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Name"
name="name"
value={name}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Username"
name="username"
value={username}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="email"
className="form-control form-control-lg"
placeholder="Enter Your E-mail Address"
name="email"
value={email}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Phone Number"
name="phone"
value={phone}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Website Name"
name="website"
value={website}
onChange={(e) => onInputChange(e)}
/>
</div>
<button className="btn btn-warning btn-block">Update User</button>
</form>
</div>
</div>
);
};
export default EditUser;
AddUser.js:
import React, { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
const AddUser = () => {
let history = useNavigate();
const [user, setUser] = useState({
name: "",
username: "",
email: "",
phone: "",
website: "",
});
const { name, username, email, phone, website } = user;
const onInputChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const onSubmit = async (e) => {
e.preventDefault();
await axios.post("http://localhost:3001/users", user);
history.push("/");
};
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h2 className="text-center mb-4">Add A User</h2>
<form onSubmit={(e) => onSubmit(e)}>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Name"
name="name"
value={name}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Username"
name="username"
value={username}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="email"
className="form-control form-control-lg"
placeholder="Enter Your E-mail Address"
name="email"
value={email}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Phone Number"
name="phone"
value={phone}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Website Name"
name="website"
value={website}
onChange={(e) => onInputChange(e)}
/>
</div>
<button className="btn btn-primary btn-block">Add User</button>
</form>
</div>
</div>
);
};
export default AddUser;
Navbar.js:
import React from "react";
import { Link, NavLink } from "react-router-dom";
const Navbar = () => {
return (
<nav className="navbar navbar-expand-lg navbar-dark bg-primary">
<div className="container">
<Link className="navbar-brand" to="/">
React App
</Link>
<button
className="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<NavLink className="nav-link" to="/">
Home
</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" to="/about">
About
</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" to="/contact">
Contact
</NavLink>
</li>
</ul>
</div>
<Link className="btn btn-outline-light" to="/users/add">
Add User
</Link>
</div>
</nav>
);
};
export default Navbar;
package.json:
{
"name": "mycrudapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"bootstrap": "^5.2.0",
"concurrently": "^7.3.0",
"json-server": "^0.17.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"json-server": "json-server --watch db.json --port 3001",
"start:dev": "concurrently \"npm start\" \"npm run json-server\"",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
使用以下方法解决错误 #1:
{
users.map((user, index) => {
return (
<tr key={index}>
...
</tr>
);
});
}
错误 #2 和 #4 相同。仔细检查
react-router-dom
中
Link
元素的使用情况,因为从 v5 到 v6 存在重大更改。这也可能有帮助:
TypeError:无法读取未定义的属性(读取“pathname”)
警告:列表中的每个子项都应具有唯一的“key”属性。
因此,当您有一个 map 函数并且它附加的每个子项都没有唯一的键时,就会出现此警告。假设您正在附加一个列表,那么只需向每个数据列表添加一个键即可解决您的问题。这里是例子
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number,id) =>
<li key={id} >{number}</li>
);
因此,在您的 Home 映射函数中添加上述键。
未捕获的 TypeError:无法读取未定义的属性(读取“pathname”)
当我们没有在 React 路由器中的 Link 组件上设置 to prop 时,会发生错误“无法读取未定义的属性‘pathname’”,因此请检查是否遗漏了一个
此外,如果您使用的是 react-router 的 v6,请像这样嵌套路由将所有用户的路由绑定在一个用户路由下,这样可以使其更具可读性。
<Route path="users">
<Route path="add" element={<AddUser />} />
<Route path=":id" element={<User />} />
<Route path="edit/:id" element={<EditUser />} />
<Route/>