Redux:无法读取未定义的属性“getState”

时间:2021-02-21 05:37:42

标签: javascript reactjs web redux react-redux

目前我正在学习 Redux 以使用 React 创建一个简单的待办事项应用程序。我就是这样做的

这是我的减速器和存储:

/redux/todo.js

const initialState = {
  items: []
};

const ADD_TODO = "ADD_TODO";

export const addTodo = (text) => ({
  type: ADD_TODO,
  payload: text
});

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_TODO":
      return {
        ...state,
        items: [...state.items, action.payload]
      };
    default:
      return state;
  }
};

export default reducer;

/redux/store.js

import { createStore, combineReducers } from "redux";

import todoReducer from "./todo";

const reducer = combineReducers({
  todo: todoReducer
});

export default createStore(reducer);

这是我要使用 redux 映射的组件:

/components/TodoApp.js

import React, { useState } from "react";

export default function TodoApp({ todos, addTodo }) {
  const [text, setText] = useState("");

  return (
    <div>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <button
        onClick={() => {
          addTodo(text);
        }}
      >
        Add
      </button>
      <ul>
        {todos.map((todo) => (
          <li>{todo}</li>
        ))}
      </ul>
    </div>
  );
}

这是我将商店与 UI 绑定的方式:

/bindings/TodoApp.js

import { connect } from "react-redux";
import TodoApp from "../components/TodoApp";
import { addTodo } from "../redux/todo";

const mapStateProps = (state) => {
  return {
    todos: state.todo.items
  };
};

const mapActionsToProps = {
  addTodo
};

export default connect(mapStateProps, mapActionsToProps)(TodoApp);

然后我在根组件中导入:

App.js

import "./styles.css";
import TodoApp from "./bindings/TodoApp";

export default function App() {
  return (
    <div className="App">
      <TodoApp />
    </div>
  );
}

`

最后,我将 Redux 添加到索引文件中:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { store } from "./redux/store";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <StrictMode>
      <App />
    </StrictMode>
  </Provider>,
  rootElement
);

这是我得到的错误:

enter image description here

请帮我处理一下,非常感谢,可以的话请修改这个codeandbox link中的代码here

再次感谢您,祝您有个美好的一天

1 个答案:

答案 0 :(得分:1)

当我看到 codeandobx 时,看到了错误 -

TypeError
store is undefined

我认为您可以从 index.js 的第 4 行的“store”中删除“{”括号,因为 store 是 store.js 文件的默认导入,而不是命名导入