简体   繁体   English

反应 useContext setState 不是函数

[英]react useContext setState is not a function

I'm working on a react app and I need to keep an array of names in my global state like on this file:我正在开发一个 React 应用程序,我需要在我的全局状态中保留一个名称数组,就像在这个文件中一样:

import React from "react";
import { useState } from "react";

const initialState = {
  nameList: [],
  test: 'hello'
}

export const Context = React.createContext()

const Data = ({ children }) => {
  const [state, setState] = useState(initialState)

  return(
    <Context.Provider value={[state, setState]}>
      {children}
    </Context.Provider>
  )
}

export default Data

However, when I try to set "nameList" to a new value in this other file:但是,当我尝试将“nameList”设置为另一个文件中的新值时:

const [state, setState] = useContext(Context);
const [currName, setCurrName] = useState('');

const handleAddName = () => {
  setState.nameList(prevState => [...prevState, currName])
}

I get a "setState.nameList is not a funtion" error and I can't find nor understand the reason why, any help would be much appreciated我收到一个“setState.nameList is not a funtion”错误,我找不到也无法理解原因,任何帮助将不胜感激

You're updating the state incorrectly, here's how to do it in your case:您错误地更新了状态,这是在您的情况下的操作方法:

const handleAddName = () => {
    setState(prevState => ({
        ...prevState,
        nameList: [...prevState.nameList, currName]
    }))
}

This will make sure that the state is updated immutably.这将确保状态不变地更新。

setState.nameList is wrong because setState is a function but not an object that will magically have the keys of your state. setState.nameList是错误的,因为setState是一个函数,而不是一个可以神奇地拥有状态键的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM