无法读取未定义的 react-redux 待办事项应用程序的属性"映射"



嗨,我试图建立一个todo应用程序,并试图在todo列表中添加todo,但我得到这个错误:

TypeError: Cannot read property 'map' of undefined

下面是错误代码:

4 | function TodoList() {
5 |   const list = useSelector((state) => state.todoList.text);
6 |   return (
>  7 |     <div>
8 |     {list.map((todo)=>{
9 |         <li>todo</li>
10 |     })}

这里是TodoList.js:

import React from "react";
import { useSelector } from "react-redux";
const TodoList = () => {
const list = useSelector((state) => state.todoList.text);
return (
<div>
{list.map((todo)=>{
<li>todo</li>
})}
</div>
);
}
export default TodoList;

这里是index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import { createStore, combineReducers, applyMiddleware } from "redux";
import { TodoReducer,TodoListReducer } from "./redux/reducers";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
const rootReducer = combineReducers({
todoList: TodoListReducer,
todos: TodoReducer
});
const middleware = [thunk];
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(...middleware))
);
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>{" "}
</React.StrictMode>,
document.getElementById("root")
);
reportWebVitals();

这里是reducers.js:

import { SET_VALUE } from "./actions";
import {ADD_TODO} from "./actions"
let initial_state = [{
text:""
}]
export const TodoReducer = (state = initial_state, action) => {
switch (action.type) {
case ADD_TODO:
return [{
text: action.text,
}]

default:
return state;
}
}
export const TodoListReducer = (state = initial_state, action) => {
switch (action.type) {
case SET_VALUE:
return {
...state,
text: action.text
}
default:
return state;
}
}

实际上我是一个新的程序员,所以我可能有很多错误:)。谢谢您的关注。

state.todoList是一个对象数组。所以像这样更新:

const list = useSelector((state) => state.todoList);

初始状态没有属性'todoList',所以该状态。todoList未定义

设置默认值,如let initial_state = {todoList:[{text:""}]}

相关内容

  • 没有找到相关文章

最新更新