【问题标题】:useContext returning undefined valuesuseContext 返回未定义的值
【发布时间】:2021-07-02 22:53:06
【问题描述】:

面对这个我的上下文返回未定义值的问题,它返回的只是初始状态。在事务列表中,我试图调用我定义的函数 deleteTransaction,但它给出的错误是它未定义。如果我遗漏了什么或需要添加什么,请告诉我。

这些是我的依赖,以防万一。

"dependencies": {
"@testing-library/jest-dom": "^5.11.10",
"@testing-library/react": "^11.2.6",
"@testing-library/user-event": "^12.8.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.1"
},

GlobalState.js:

import React, { createContext, useReducer } from 'react'
import AppReducer from './AppReducer'

const initialState = {
transactions: [
    {id:1, text:"Flower", amount:-20},
    {id:2, text:"Salary", amount:300},
    {id:3, text:"Book", amount:-10},
    {id:4, text:"Camera", amount:150}
]
}

export const GlobalContext = createContext(initialState)

export const GlobalProvider = (props) => {
const [state, dispatch] = useReducer(AppReducer, initialState)

const deleteTransaction = (id) => {
    dispatch({type:'DELETE_TRANSACTION', payload:id})
}

return (<GlobalContext.Provider value={{transactions:state.transactions, deleteTransaction}}>
    {props.children}
</GlobalContext.Provider>)
}

AppReducer.js:

export default (state, action) => {
switch(action.type) {
    case 'DELETE_TRANSACTION':
        return {
            ...state,
            transactions: state.transactions.filter(transaction => transaction.id !== action.payload)
        }
    default:
        return state
}
}

TransactionList.js:

import React, { useContext } from 'react'
import { GlobalContext } from '../context/GlobalState'
import { Transaction } from './Transaction'

export const TransactionList = () => {

const { transactions } = useContext(GlobalContext)

return (
    <>
        <h3>History</h3>
        <ul className="list">
            {transactions.map(transaction => (
                <Transaction key={transaction.id} {...transaction} />
            ))}
        </ul>
    </>
)
}

Transaction.js:

import React, { useContext } from 'react'
import { GlobalContext } from '../context/GlobalState'

export const Transaction = ({id, text, amount}) => {

const {deleteTransaction} = useContext(GlobalContext)

const sign = amount < 0 ? "-" : "+"

return (
    <div>
        <li className={amount < 0 ? "minus" : "plus"}>
            {text} <span>{sign}${Math.abs(amount)}</span><button onClick={() => 
deleteTransaction(id)} className="delete-btn">x</button>
        </li>
    </div>
)
}

【问题讨论】:

  • 你需要在你想使用上下文的地方用GlobalProvider 包裹你的组件
  • 你的 GlobalProvider 是否在 TransactionList 组件的父层次结构中
  • 真是个愚蠢的错误。我对 React 不是很有经验,但我知道我是如何忘记用我的 GlobalProvider 来完成它的。谢谢你的时间。现在一切正常。

标签: reactjs use-context


【解决方案1】:

问题

您的默认上下文值缺少deleteTransaction 函数。

const initialState = {
  transactions: [
    {id:1, text:"Flower", amount:-20},
    {id:2, text:"Salary", amount:300},
    {id:3, text:"Book", amount:-10},
    {id:4, text:"Camera", amount:150}
  ]
}

export const GlobalContext = createContext(initialState)

解决方案

定义上下文的默认值形状以匹配组件使用的内容,并确保 Transaction 在 React 树中的上方有一个 GlobalContext.Provider

const defaultValue = {
  transactions: [],
  deleteTransaction: () => {}, // <-- add a deleteTransaction function
}

export const GlobalContext = createContext(defaultValue);

Updating Context from a Nested Component

经常需要从一个组件更新上下文 嵌套在组件树深处的某个地方。在这种情况下,您可以 通过上下文向下传递函数以允许消费者更新 上下文。

theme-context.js

// Make sure the shape of the default value passed to
// createContext matches the shape that the consumers expect!
export const ThemeContext = React.createContext({
  theme: themes.dark,
  toggleTheme: () => {},
});

【讨论】:

  • 这不是上下文的初始状态,它是使用的值,如果层次结构中没有提供者
  • @ShubhamKhatri OP 将其称为初始状态,我最初只是使用了与他们相同的名称,但您是对的,createContext 采用默认值。
猜你喜欢
  • 2019-12-24
  • 2023-04-06
  • 2020-12-08
  • 1970-01-01
  • 2021-07-19
  • 2019-12-13
  • 1970-01-01
相关资源
最近更新 更多