在状态中更新状态时,.map()不是函数

时间:2020-08-15 06:14:39

标签: reactjs react-context react-beautiful-dnd

更新状态时,我收到以下错误消息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()后,我注意到ColumnDroppable中的noteList仍然是数组类型,但不是100%引发错误的原因。

我还注意到,在setNoteAsOpen()内,openNotes的状态在调用setOpenNotes()之后仍然相同。好像setOpenNotes()没有更新状态。我不确定这是否与问题相关或导致了问题,但我想我也会指出。

谢谢!

1 个答案:

答案 0 :(得分:1)

据我所知,当react第一次渲染组件时,context的值可能不会初始化,因此map不会是一个函数! 尝试提供一个空数组作为context的默认值,

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_validate, KFold
from sklearn.multioutput import MultiOutputClassifier
clf=MultiOutputClassifier(RandomForestClassifier(random_state=42,class_weight="balanced"))
k_fold = KFold(n_splits=5, shuffle=True, random_state=42)

scores = cross_validate(clf, X_train_tf, y_train, cv=k_fold, scoring=['f1_weighted'])

它应该解决问题