目前,我正在尝试在react.js中将
useReducer
与localStorage
一起使用,并实现了小型Reducer tasks
。
几乎所有我都通过使用 localStorage 设置了
tasks
,但无法从中访问 text
。 (它显示了空数组)
我已经设置了
initialTasks
这样:不知道我在这里错过了什么。
以下是我的试用代码的一些片段:
...
import tasksReducer from "./tasksReducer";
const initialTasks = {
tasks:
localStorage.getItem("tasks") == null
? []
: JSON.parse(localStorage.getItem("tasks")),
};
export default function ReducerPrac() {
const [{ tasks }, dispatch] = useReducer(
tasksReducer,
{
tasks: [],
},
initialTasks
);
const tasksId = useRef(0);
function handleAddTask(text) {
dispatch({
type: "added",
id: tasksId.current + 1,
text: text,
});
}
function handleChangeTask(text) {
dispatch({
type: "changed",
text: text,
});
}
function handleDeletetask(taskId) {
dispatch({
type: "deleted",
id: taskId,
});
}
useEffect(() => {
localStorage.setItem("tasks", JSON.stringify(tasks));
}, [tasks]);
return (
<>
<h3>Reducer todo</h3>
<AddTask onAddTask={handleAddTask} />
<br />
<TaskList
tasks={tasks}
onChangeTask={handleChangeTask}
onDeleteTask={handleDeletetask}
/>
</>
);
}
export default function tasksReducer(tasks, action) {
switch (action.type) {
case "added": {
return [
...tasks,
{ id: action.id, text: action.text, done: false },
];
}
case "changed": {
return tasks.map((t) => {
if (t.id === action.text.id) {
return action.text;
} else {
return t;
}
});
}
case "deleted": {
return tasks.filter((t) => t.id !== action.id);
}
default: {
throw new Error("Unknown dispatched action" + action.type);
}
}
}
而且我也遇到了这个错误:
react-dom.development.js:16548 Uncaught TypeError: init is not a function
at mountReducer (react-dom.development.js:16548:1)
at Object.useReducer (react-dom.development.js:17682:1)
at useReducer (react.development.js:1626:1)
at ReducerPrac (ReducerPrac.js:15:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
注意:我已经搜索了下面列出的所有堆栈溢出问题,但对我不起作用:(在第二个链接中他们也提到了
useContext
)
非常感谢您的帮助!
PS:一个问题是是否需要在reactjs中将
useContext
与useReducer
和localStorage
一起使用。
useReducer
只需 2 个参数
useReducer(
tasksReducer,
initialTasks
);