【问题标题】:how to use mapdispatchtostate in reudx?如何在 redux 中使用 mapdispatchtoprops?
【发布时间】:2020-06-03 13:01:27
【问题描述】:

这是文件 list.js

...
class List extends React.Component {
  render() {

    return (
        ...    
          {this.props.todoList.map((todo, index) => <Item {...todo} key = {index}/>)} // err this code
        ...
    );
  }
};
const mapStateToProps = (state) => {
  return {
    todoList: state.todos 
  };
};
...

这是文件 rootReducers.js

const initialState = {
    todos : [
        { id: 1, name: "Khoa" },
        { id: 2, name: "Khoai" },
        { id: 3, name: "Kha" }
      ],
      currentName : ''
}

const TodoList = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_TODO":
      return [...state.todos, { id: state.todos.length + 1, name: action.text }];
    default:
      return state;
  }
};
...

这是 action.js

export const addTodo = (text) =>{
    return {
        type : 'ADD_TODO',
        text
    }
}

这是来自Create.js 的文件

...
const mapDispatchToProps = (dispatch) => {
  return {
    addTodo: (text) => dispatch(addTodo(text))
  };
};
...

我加载数据成功但是,当我执行事件添加到它消息:无法读取未定义的属性“地图”。帮帮我

【问题讨论】:

  • 显示createStore代码
  • id: state.todos.length + 1 这行会在你实现删除待办事项时给你带来麻烦。您可以执行以下操作以防止出现问题:const createId = ((counter) =&gt; counter++)(initialState.todos.length);。添加待办事项时,您可以执行以下操作:id:createId()。如果您打算使用 localstorage 持久化状态,那么您必须在中间件中设置 id,因为 id 取决于您的待办事项列表中已经使用的 id。

标签: javascript redux react-redux frontend


【解决方案1】:

您的减速器代码似乎错误。您需要从中返回完整的新状态切片,而不仅仅是一个数组。

const TodoList = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_TODO":
      return {
        ...state,
        todos: [...state.todos, { id: state.todos.length + 1, name: action.text }]
      };
    default:
      return state;
  }
};

【讨论】:

    猜你喜欢
    • 2019-12-19
    • 1970-01-01
    • 2018-01-18
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2020-10-15
    相关资源
    最近更新 更多