【问题标题】:React.js TypeError: Invalid attempt to destructure non-iterable instance [duplicate]React.js TypeError:解构不可迭代实例的无效尝试[重复]
【发布时间】:2020-01-10 01:00:44
【问题描述】:

我用 Hooks 制作了简单的“待办事项列表”。

这个错误没有揭示问题出在哪里,所以我不知道在哪里解决它。 我搜索了解决此错误的提示,但我能找到一点。

此错误消息对我的代码意味着什么?

这是我的代码。

//actions.js
export const addTodo = todo => ({
  type: 'ADD_TODO',
  payload: {todo: todo}
})

//reducers.js
export const todoReducer = (state, action) => {
  switch(action.type){
    case 'ADD_TODO':
      return { todoList: [...state.todo, action.payload]};
    default:
      return state;
  }
}

//store.js
import * as React from 'react'
import { todoReducer } from "./reducers";

const initialState = {
  todoList: [],
}

export const Store = React.createContext(initialState)

export const StoreProvider = ({children}) => {
  const [state, dispatch] = React.useReducer(todoReducer, initialState)
  return (
    <Store.Provider value={{state, dispatch}}>{children}</Store.Provider>
  )
}
//component.jsx
import React from "react";
import { Store } from "./store";

const TODOLIST = () => {
  const [state, dispatch] = React.useContext(Store)
  return(
    <>
      <button onClick={() => dispatch({type: 'ADD_TODO', payload: state.todo})}>ADD</button>
      <ul>
        {state.todoList.map((tl, index) =>
          <li key={index}>{tl}</li>)}
      </ul>
    </>
  )
}

export default TODOLIST
//App.jsx
import TODOLIST from './component';

function App() {
  return (
    <>
      <TODOLIST />
    </>
  );
}

export default App;

//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { StoreProvider } from "./store";

ReactDOM.render(
  <StoreProvider>
      <App />
  </StoreProvider>,
document.getElementById('root'));

【问题讨论】:

  • “无效的解构不可迭代实例的尝试” 与 React 无关,这意味着您已经(或您调用的某些代码)完成了 [/* ... */] = something[...something] 你不能用 something 做到这一点。
  • 你有[...state.todo,你的意思是[...state.todoList吗?
  • 提供者的值是一个对象,但是你正在解构一个数组,这也可能导致错误:const [state, dispatch] = React.useContext(Store)

标签: javascript reactjs react-hooks


【解决方案1】:

纠正这个

export const todoReducer = (state, action) => {
  switch(action.type){
    case 'ADD_TODO':
      return { todoList: [...state.todoList, action.payload.todo]};
    default:
      return state;
  }
}

当您将 todo 对象传递给有效负载时

export const addTodo = todo => ({
  type: 'ADD_TODO',
  payload: {todo: todo}
})

【讨论】:

  • 还有,...state.todoList
  • @EmileBergeron 是的,谢谢
  • 谢谢你们!我可以理解这个错误的更多含义,但是在我按照您提出的代码更正后,此错误消息不会改变。
  • 我认为商店或提供者存在问题,可以传达某些信息。我该如何解决这个错误? TODOLIST src//component.jsx:4 1 | import React from "react"; 2 | import { Store } from "./store"; 3 | &gt; 4 | const TODOLIST = () =&gt; { 5 | const [state, dispatch] = React.useContext(Store) 6 | return( 7 | &lt;&gt;
猜你喜欢
  • 2021-10-10
  • 2016-12-14
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 2019-06-17
相关资源
最近更新 更多