【问题标题】:Cannot read property 'map' of undefined react-redux todo app无法读取未定义的 react-redux todo 应用程序的属性“地图”
【发布时间】:2021-11-02 22:21:05
【问题描述】:

您好,我正在尝试构建一个待办事项应用程序并尝试在待办事项列表中添加待办事项,但我收到此错误:

TypeError: 无法读取未定义的属性“地图”

这里是错误代码:

   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;
    }
}

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

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

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

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

    【讨论】:

    • 哦,谢谢!但是现在我得到了这个错误: TypeError: list.map is not a function 直到我在我的栏上写任何东西都没有问题。当我在栏中写一个字符时,突然我得到错误代码。
    • 应该返回return [{ text:action.text }]
    【解决方案2】:

    初始状态没有属性“todoList”,因此 state.todoList 未定义。

    为它设置一个默认值,例如let initial_state = {todoList:[{text:""}]}

    【讨论】:

    • 您好,感谢您的关注!我按照您所说的更改了代码,但是更改代码时出现此错误: TypeError: list.map is not a function
    猜你喜欢
    • 2017-02-21
    • 1970-01-01
    • 2019-03-19
    • 2019-02-25
    • 2019-10-29
    • 1970-01-01
    • 2020-07-23
    • 2019-04-26
    • 2019-02-08
    相关资源
    最近更新 更多