我正在制作reactjs
待办事项应用程序。
在components文件夹中,我有2个文件TodoList.js和TodoDetails.js。
在TodoLis.js中,我有道具作为道具() 传递给TodoDetails.js。 但是,由于TodoDetails.js中的项目未定义(li和div标签中的项目),因此出现错误。 如何解决该问题并呈现待办事项清单(目前已进行硬编码)?
我添加了TodoContexts.js。 TodoContextProvider位于App.js中。
TodoList.js
import React, { useContext } from 'react';
import TodoDetails from './TodoDetails';
import { TodoContext } from '../contexts/TodoContexts';
const TodoList = () => {
const { items } = useContext(TodoContext);
return items.length ? (
<div className="todo-list">
<ul>
{items.map(item => {
return ( <TodoDetails item={item} key={item.id} /> )
console.log(item, "item");
})}
</ul>
</div>
) : (
<div className="empty">
You have no todos at the moment.
</div>
)
}
export default TodoList
TodoDetails.js
import React, { useContext } from 'react';
import { TodoContext } from '../contexts/TodoContexts';
const TodoDetails = ({ item }) => { //TodoList item is props
const { removeItems } = useContext(TodoContext);
return (
<li onClick={() => removeItems(item.id)}>
<div className="items">{item.items}</div>
<div className="date">{item.date}</div>
</li>
)
}
export default TodoDetails
import React, { createContext, useState } from 'react';
import { v4 as uuidv4 } from 'uuid'; //npm install uuid
export const TodoContext = createContext();
const TodoContextProvider = (props) => {
const [items, setItems] = useState([
{items: 'laundry', date: '2020-11-18', id: 1},
{items: 'lunch', date: '2020-11-20', id: 2},
]);
const addItems = (items, date) => {
setItems([...items, {items, date, id: uuidv4()}]);
};
const removeItems = (id) => {
setItems(items.filter(item => item.id !== id));
};
return (
<TodoContext.Provider value={{ items, addItems, removeItems }}>
{props.children}
</TodoContext.Provider>
)
}
export default TodoContextProvider
App.js
import React from 'react';
import Navbar from './components/Navbar';
import Form from './components/Form';
import TodoList from './components/TodoList';
import TodoContextProvider from './contexts/TodoContexts';
import TodoDetails from './components/TodoDetails';
function App() {
return (
<div className="App">
<TodoContextProvider>
<Navbar />
<Form />
<TodoList />
<TodoDetails />
</TodoContextProvider>
</div>
);
}
export default App;
答案 0 :(得分:0)
问题是createContext无法正确初始化,您需要执行以下操作:
createContext({
items: [],
addItems: () => {},
removeItems:() => {}
})
就像您构造上下文一样