我正在開發一個 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
但是,當我嘗試將“nameList”設定為另一個檔案中的新值時:
const [state, setState] = useContext(Context);
const [currName, setCurrName] = useState('');
const handleAddName = () => {
setState.nameList(prevState => [...prevState, currName])
}
我收到一個“setState.nameList is not a funtion”錯誤,我找不到也無法理解原因,任何幫助將不勝感激
uj5u.com熱心網友回復:
您錯誤地更新了狀態,這是在您的情況下的操作方法:
const handleAddName = () => {
setState(prevState => ({
...prevState,
nameList: [...prevState.nameList, currName]
}))
}
這將確保狀態不變地更新。
setState.nameList是錯誤的,因為它setState是一個函式,而不是一個可以神奇地擁有狀態鍵的物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/329672.html
標籤:javascript 反应 反应原生
上一篇:React基于物件初始化狀態
