簡體   English   中英

當 state 在上下文中更新時,.map() 不是 function

[英].map() is not a function when state is updated in Context

更新 state 時,我收到以下錯誤消息noteList.map is not a function

我有以下設置

src/pages/index.js我的 DragDropContainer 正在安裝的位置

const Index = ({ data, location }) => {
  // instantiate a map of notes
  const noteMap = new Map()
  for (const brainNote of data.allBrainNote.nodes) {
    const key = "/" + brainNote.slug
    noteMap.set(key, brainNote)
  }
  return (
    <Provider noteMap={noteMap} openNotes={[data.brainNote]}>
      <DragDropContainer location={location}></DragDropContainer>
    </Provider>
  )
}

src/components/DragDropContainer.js

import React, { useContext } from "react"
import { DragDropContext } from "react-beautiful-dnd"
import ColumnDroppable from "../components/columnDroppable"
import { Consumer, Context } from "../utils/notesContext"

...

const DragDropContainer = ({ location }) => {
  const notesContext = useContext(Context)
  const { openNotes, setOpenNotes } = notesContext

  ...

  return (
    <div>
      <div>
        <div style={{ display: "flex" }}>
          <DragDropContext onDragEnd={onDragEnd}>
            <Consumer>
              {context => (
                <div>
                  {context.openNotes.map((noteList, ind) => (
                    <ColumnDroppable
                      key={ind}
                      index={ind}
                      noteList={noteList}
                      location={location}
                    />
                  ))}
                </div>
              )}
            </Consumer>
          </DragDropContext>
        </div>
      </div>
    </div>
  )
}

export default DragDropContainer

src/components/columnDroppable.js

const ColumnDroppable = ({ index, noteList, location }) => {
  return (
    <Droppable key={index} droppableId={`${index}`}>
      {provided => (
        <div ref={provided.innerRef} {...provided.draggableProps}>
          {noteList.map((note, noteIdx) => ( // when updated this line throws an error
            <NoteContainer
              key={note.title}
              title={note.title}
              note={note}
              noteId={note.title}
              location={location}
              slug={note.slug}
              noteIdx={noteIdx}
            ></NoteContainer>
            // <Note key={note.id} title={note.title} note={note} note noteIdx={noteIdx} />
          ))}
          {provided.placeholder}
        </div>
      )}
    </Droppable>
  )
}

ColumnDroppable.propTypes = {
  index: PropTypes.node.isRequired,
}

export default ColumnDroppable

src/utils/notesContext.js

export const Context = createContext({})

export const Provider = props => {
  const { noteMap: initNoteMap, openNotes: initNote, children } = props

  const [noteMap, setNoteMap] = useState(initNoteMap)
  const [openNotes, setOpenNotes] = useState([initNote]) // openNotes is a 2D array

  const setNoteAsOpen = slug => {
    // note map has the key set to the slug of a note
    const isNoteAlreadyOpen = openNotes.some(note => {
      return note.slug === slug.slice(1)
    })
    if (isNoteAlreadyOpen) return // note is already open

    const openingNote = noteMap.get(slug)
    setOpenNotes([...openNotes, openingNote])
  }

  const notesContext = {
    noteMap,
    setNoteMap,
    openNotes,
    setOpenNotes,
    setNoteAsOpen,
  }

  return <Context.Provider value={notesContext}>{children}</Context.Provider>
}

export const { Consumer } = Context

src/components/CustomLinkToDraggable.js這是調用 setNoteAsOpen() 的地方

...
export const LinkToDraggableNote = React.forwardRef(
  ({ to, onClick, onMouseLeave, onMouseEnter, ...restProps }, ref) => {
    const notesContext = useContext(Context)
    const { openNotes, setNoteAsOpen } = notesContext

    const onClickHandler = ev => {
      console.log("within onclick handler")
      ev.preventDefault()

      setNoteAsOpen(to)
    }
    ...
   return (
      <Link
        {...restProps}
        to={to}
        ref={ref}
        onClick={onClickHandler}
        onMouseEnter={onMouseEnterHandler}
        onMouseLeave={onMouseLeaveHandler}
      />
    )

調用setNoteAsOpen()后,我注意到noteList中的 noteList 仍然是數組類型,但不是 100% 拋出錯誤的原因。

我還注意到,在setNoteAsOpen()中,調用 setOpenNotes setOpenNotes() ) 后openNotes state 仍然相同。 好像setOpenNotes()沒有更新 state。 我不確定這是否相關或導致問題,但我想我也會指出這一點。

提前致謝!

據我所知,當 react 第一次渲染組件時, context 的值可能沒有被初始化,所以 map 不會是 function,嘗試給一個空數組作為 context 的默認值,

{(context=[])=> (
        <div>
            {context.openNotes.map((noteList, ind) => (
              <ColumnDroppable
                   key={ind}
                   index={ind}
                   noteList={noteList}
                   location={location}
                 />
               )}

它應該解決問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM